【问题标题】:C++ Using std::set<> in std::map<>C++ 在 std::map<> 中使用 std::set<>
【发布时间】:2014-04-15 04:11:31
【问题描述】:

我想在 std::map 中使用 std::set

我对 std:: 容器没有太多经验,所以我不确定我是否正确使用它。 我正在尝试处理一组值,并且每组中都有另一组值。

map<string, set<string> > data_map;

data_map["KEY1"].insert("VAL1");
data_map["KEY1"].insert("VAL2");

data_map["KEY2"].insert("VAL1");
data_map["KEY2"].insert("VAL3");

当我尝试访问地图中的集合时出现错误(内部循环)

error: no match for call to ‘(std::set<std::basic_string<char> >) ()’|
error: no match for call to ‘(std::set<std::basic_string<char> >) ()’|


for( map<string, set<string> >::iterator mip = data_map.begin();mip != data_map.end(); ++mip) {
    for ( set<string>::iterator sit = mip->second().begin(); sit != mip->second().end(); ++sit )
        cout << *sit << endl;

}

您能告诉我如何迭代所有值吗?

【问题讨论】:

  • 你只想要second,而不是second()(它是std::pair的一个字段,不是一个方法)。这能解决您的问题吗?
  • @JeremyRoman 对不起,你是对的。谢谢!

标签: c++ map iterator set


【解决方案1】:
mip->second().begin()

应该是

mip->second.begin()

【讨论】:

    【解决方案2】:

    你应该使用 mip->second 而不是 mip->second()。 我建议您在 for-each 循环中使用 auto。

    for(auto mip : data_map)
    {  
        //Do another loop to get the values of your set, to get the set from the map use get<1>(mip);
    
    }
    

    以这种方式阅读更好,错误的空间更少。

    【讨论】:

    • 如果你打算使用auto,你大概是在 C++11 中。那时您不妨使用基于范围的 for。
    【解决方案3】:

    不要像函数一样调用集合。

    for( map<string, set<string> >::iterator mip = lines.begin();mip != lines.end(); ++mip) {
        for ( set<string>::iterator sit = mip->second.begin(); sit != mip->second.end();
              ++sit )
            cout << *sit << endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-10
      • 2021-05-30
      • 2020-04-01
      • 1970-01-01
      • 2017-07-28
      • 2012-09-28
      • 1970-01-01
      • 2014-06-06
      相关资源
      最近更新 更多