迭代到字符串集,这些字符串是映射中的值
Iterating in to the set of strings which are the values in map
#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_type
的const&
,即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
,但你可以有多个值对应于一个键值。但是,与您的解决方案不同,具有相同键的值的顺序是其插入的顺序。
现场演示
相关文章:
- 如何使用Visual Studio 2008将字符串映射到函数?
- 我可以比朴素哈希表更快地将随机字符串映射到两个类吗?
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 在声明unordered_map的错误中,将字符串映射到模板
- 将字符串映射到矢量或将不同的键映射到一个值
- 使用 C++11 可变参数模板初始化枚举到字符串映射
- 将字符串映射到 C++ 中的类函数
- 根据该输入字符串将字符串映射到不同的类
- 如何访问 <int,字符串>映射中的特定字符?
- C字符串映射键
- C 索引中的字符串映射而无需分配
- 实现将字符串映射到 C++ 中的数组的哈希表。我一直在"Debug Assertion Failed",我不知道为什么
- 将字符串映射到无符号 int 到无符号 int 的映射
- C++ std::将字符串映射到指针
- c++将大型数字字符串映射到数字字符串范围
- 使用字符串映射的向量时可能会发生内存泄漏C++
- 一个比较2个字符串映射的通用C++规则引擎
- 如何在c++中仅针对键的子集有效地比较两个字符串映射
- 如何将用户输入(字符串)映射到Enum值
- 我如何消除这个枚举到字符串映射代码的样板文件?