【问题标题】:read set from map in c++从 C++ 中的地图读取集合
【发布时间】:2015-09-18 22:33:36
【问题描述】:

这是一个非常愚蠢的问题,但不知何故我无法解决。

我有映射,键是字符串,值已设置,我想遍历值并打印它,例如

std::map<std::string, std::set<std::string>> test_map_set

for (auto it_map = test_map_set["test"].begin(); it_mpa != test_map_set["test"].begin(); it_map ++ )
{
  auto it = it_map->second;  ===> Here I am getting error that it has no member second
  then iterate through set 
}

我的问题是如何遍历集合?

【问题讨论】:

  • 您已经在迭代集合(映射到“test”),只需取消引用指针以获取该特定集合的元素。如果您想遍历地图,请删除 ["test"],这可能是您想要的。也使用 .end() 代替第二个 .begin()
  • 您的it_map 实际上是key = "test" 集合的迭代器。所以当然,集合迭代器没有second 成员(实际上第二个是一对成员)。

标签: c++ dictionary iterator std


【解决方案1】:

确实std::string 没有成员second

既然有了c++11,就可以让生活轻松很多:

std::map<std::string, std::set<std::string>> test_map_set

for (std::string& set_element : test_map_set["test"])
{
}

删除:

auto& test = test_map_set["test"];
for (auto it = test.begin(); it!= test.end();)
{
    if (it->length()==5)
        it = test.erase(it);
    else
        ++it;
}

这将删除所有 5 个字符的字符串

【讨论】:

  • 你的解决方案对我有用。还有一个问题,如果我从地图中删除元素,它会自动指向下一个元素
  • 用你的答案更新问题
  • 在得到有用的答案后完全改变问题是不礼貌的。它使答案看起来错误,没有人得到信任。此外,这种组合将不再对其他人有用,这使我也倾向于投反对票和投票结束。 更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 2020-02-03
  • 2019-04-30
  • 2021-12-13
相关资源
最近更新 更多