[英]Iterator loop in C++
我已经为此搜索了很长时间,但是我找不到答案。 我发现的大部分样本都是基于对向量,地图等进行迭代。
我有下面的代码。
multimap<int, int>::iterator it = myMuliMap.find(1);
假设我有三对密钥为“ 1”的密钥。 我喜欢从for循环中获得这三对。我认为我不能使用for(multimap :: iterator anotherItr = myMuliMap.begin()..
下面的代码在C#中。我想获得C ++版本。
foreach(var mypair in it){
Console.WriteLine(mypair.Key);
}
您要寻找的功能是equal_range。 这会将迭代器返回到映射中与指定键匹配的所有对
auto range = myMultiMap.equal_range(1);
for ( auto it = range.first; it != range.second; ++it) {
...
}
编辑
没有自动版本
pair<multimap<int,int>::const_iterator,multimap<int,int>::const_iterator>> it = myMultiMap.equal_range(1);
for ( multimap<int,int>::const_iterator it = range.first;
it != range.second;
++it) {
...
}
使用std::equal_range()
:
int tolookfor = 1;
typedef multimap<int, int>::iterator iterator;
std::pair<iterator, iterator> p =
std::equal_range(myMuliMap.begin(), myMuliMap.end(), tolookfor);
for (iterator it = p.first; it != p.second ++it)
std::cout << (*it).second << std::endl;
multi_map的成员函数equal_range
工作原理类似:
std::pair<iterator, iterator> p =
myMuliMap.equal_range(tolookfor);
这只会打印出由
std::pair<std::multimap<int, int>::iterator, std::multimap<int, int>::iterator> result;
result = myMultimap.equal_range(1);
for(std::multimap<int,int>::iterator it = result.first; it != result.second; it++)
{
std::cout << it->first << " = " << it->second << std:: endl;
}
您可以使用类似以下循环的内容。
for (std::multimap<int, int>::iterator i = myMultiMap.lower_bound(1);
i != myMultiMap.upper_bound(1);
++i)
{
std::cout << i->first << " => " << i->second << '\n';
}
这在当前版本的C ++中有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.