[英]Iterating over all pairs of elements in std-containers (C++)
What's the best way to iterate over all pairs of elements in std container like std::list
, std::set
, std::vector
, etc.? 迭代std容器中所有元素对的最佳方法是什么,如std::list
, std::set
, std::vector
等?
Basically to do the equivalent of this, but with iterators: 基本上做相当于这个,但与迭代器:
for (int i = 0; i < A.size()-1; i++)
for(int j = i+1; j < A.size(); j++)
cout << A[i] << A[j] << endl;
The easiest way is just rewriting the code literally: 最简单的方法就是直接重写代码:
for (auto i = foo.begin(); i != foo.end(); ++i) {
for (auto j = i; ++j != foo.end(); /**/) {
std::cout << *i << *j << std::endl;
}
}
Replace auto
with a const_iterator for C++98/03. 用C ++ 98/03的const_iterator替换auto
。 Or put it in its own function: 或者把它放在自己的功能中:
template<typename It>
void for_each_pair(It begin, It end) {
for (It i = begin; i != end; ++i) {
for (It j = i; ++j != end; /**/) {
std::cout << *i << *j << std::endl;
}
}
}
Just to traverse, use const_iterators. 要遍历,请使用const_iterators。 If you want to modify values, use iterator. 如果要修改值,请使用迭代器。
Example: 例:
typedef std::vector<int> IntVec;
IntVec vec;
// ...
IntVec::const_iterator iter_cur = vec.begin();
IntVec::const_iterator iter_end = vec.end();
while (iter_cur != iter_end) {
int val = *iter_cur;
// Do stuff with val here
iter_cur++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.