迭代到字符串集,这些字符串是映射中的值

Iterating in to the set of strings which are the values in map

本文关键字:字符串 映射 迭代      更新时间:2023-10-16
#include <iostream>
using namespace std;
void insertValue(map<string, set<string> >& myMap,
    string const& key,
    string const& value)
{
    // Check whether there is already a set given the key.
    // If so, insert to the existing set.
    // Otherwise, create a set and add it to the map.
    map<string, set<string> >::iterator found = myMap.find(key);
    if (found != myMap.end())
    {
        cout << "Adding '" << value << "' to an existing set of " << key << "s.n";
        found->second.insert(value);
    }
    else
    {
        cout << "Adding '" << value << "' to a new set of " << key << "s.n";
        set<string> temp;
        temp.insert(value);
        myMap.insert(make_pair(key, temp));
    }
}
int main()
{
    map<string, set<string> > filemap;
    insertValue(mymap, "file1", "path1");
    insertValue(mymap, "file1", "path2");
    insertValue(mymap, "file1", "path3");
    insertValue(mymap, "file2", "path1");
    insertValue(mymap, "file3", "path2");
    return 0;
}

谁能告诉我如何在上面的映射中给定一个键来迭代字符串集???? 还是我必须在值中放置一个迭代器....我不明白我怎么能走得更远

遍历map的最简单方法是使用基于范围的for而不是使用迭代器

for(auto const& kv : mymap) {
    for(auto const& v : kv.second) {
        std::cout << kv.first << ": " << v << 'n';
    }
}

kv是地图value_typeconst&,即std::pair<const std::string, std::set<std::string>>。然后,嵌套的 for 语句将迭代pair中的第二个元素。

如果你真的想使用迭代器,那么使用这个

for(auto miter = mymap.cbegin(); miter != mymap.cend(); ++miter) {
    for(auto siter = miter->second.cbegin(); siter != miter->second.cend(); ++siter) {
        std::cout << miter->first << ": " << *siter << 'n';
    }
}

除此之外,插入值的函数可以简化很多。在插入值之前,无需检查元素是否已存在于map中,因为如果不存在元素,map::operator[]将构造您传递给它的键,并且相应的值类型将是值初始化。因此,您的insertValue函数变成了单行代码。

void insertValue(map<string, set<string> >& myMap,
    string const& key,
    string const& value)
{
    myMap[key].insert(value); // default construct a set for a new key
}

最后,除非需要对键对应的值进行排序,否则可以改用multimap。这个容器就像一个map,但你可以有多个值对应于一个键值。但是,与您的解决方案不同,具有相同键的值的顺序是其插入的顺序。

现场演示