【问题标题】:finding the largest set within a map在地图中找到最大的集合
【发布时间】:2018-03-26 03:09:59
【问题描述】:

所以我需要帮助来查找名字最多的姓氏。然后我需要打印出名字。我已经让它打印出每个姓氏中的所有名字,但我不知道如何只打印名字最多的那个。

#include <stdio.h>
#include <iostream>
#include <string>
#include <set>
#include <map>
using namespace std;

typedef set <string> fnset;

main()
{
  map <string, fnset *> lnames;
  map <string, fnset *>::iterator lnit;
  fnset *fnames;
  fnset::iterator fnit;
  string fn, ln;

  while (cin >> fn >> ln) {
    lnit = lnames.find(ln);
    if (lnit == lnames.end()) {
       fnames = new fnset;
       lnames.insert(make_pair(ln, fnames));
    } else {
      fnames = lnit->second;
    }
    fnames->insert(fn);
   }

   for (lnit = lnames.begin(); lnit != lnames.end(); lnit++) {    
    fnames = lnit->second;
    for (fnit = fnames->begin(); fnit != fnames->end(); fnit++) {
        cout << *fnit << endl;
    }
  }
 }

【问题讨论】:

  • 好像你把这个弄得太复杂了。为什么映射 pointers 中的值通过 typedef 指向一组字符串?一个简单的map&lt;string, set&lt;string&gt;&gt; 就足够了。最后,您不需要嵌套循环,只需一个循环即可找到映射中的哪个键对应于集合中条目最多的值,然后是第二个循环打印出集合的内容。
  • 所以你有一个姓氏和名字的地图(姓氏是关键),你想找到名字最多的姓氏?请注意,有效的 C++ 只定义了一个 main(),它返回一个 int

标签: c++ set maps


【解决方案1】:

您可以从&lt;algorithm&gt; 库中调用std::max_element。它的重载之一具有以下形式。

 ForwardIt max_element( ForwardIt first, ForwardIt last, Compare comp );

firstlast 以及容器的迭代器,comp 是用于比较两个元素的比较函数对象。欲了解更多信息,请查看 cppreference 页面,http://en.cppreference.com/w/cpp/algorithm/max_element

#include <algorithm>

auto largest = std::max_element(
    lnames.begin(), lnames.end(), [](auto const& p1, auto const& p2) {
        return p1.second->size() < p2.second->size();
    });

for (auto const& name : *largest->second)
    std::cout << name << '\t';

【讨论】:

    【解决方案2】:

    我强烈建议在这里使用multimap&lt;string, string&gt; lnames。你可以这样填充它:

    for(string fn, ln; cin >> fn >> ln;) {
        lnames.insert(make_pair(ln, fn));
    }
    

    然后只需使用带有multimap::upper_bound 的迭代器来找到最大的:

    auto max_start = cbegin(lnames);
    auto max_end = cbegin(lnames);
    size_t max_distance = 0U;
    
    for(auto it_start = cbegin(lnames), it_finish = cbegin(lnames); it_start != cend(lnames); it_start = it_finish) {
        it_finish = lnames.upper_bound(it_finish->first);
    
        auto it_distance = distance(it_start, it_finish);
    
        if(it_distance > max_distance) {
            max_distance = it_distance;
            max_start = it_start;
            max_finish = it_finish;
        }
    }
    

    最后输出这个只需使用ostream_iterators:

    copy(max_start, max_finish, ostream_iterator<string>(cout, " "))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      相关资源
      最近更新 更多