迭代 std 容器中的所有元素对 (C++)

发布于 2024-08-13 00:56:11 字数 300 浏览 2 评论 0原文

迭代 std 容器中所有元素对的最佳方法是什么,例如 std::liststd::setstd::vector , ETC。?

基本上与此等效,但使用迭代器:

for (int i = 0; i < A.size()-1; i++)
    for(int j = i+1; j < A.size(); j++)
        cout << A[i] << A[j] << endl;

What's the best way to iterate over all pairs of elements in std container like std::list, std::set, std::vector, etc.?

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一生独一 2024-08-20 00:56:11

最简单的方法就是按字面意思重写代码:

for (auto i = foo.begin(); i != foo.end(); ++i) {
  for (auto j = i; ++j != foo.end(); /**/) {
     std::cout << *i << *j << std::endl;
  }
}

auto 替换为 C++98/03 的 const_iterator。或者将其放在自己的函数中:

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;
    }
  }
}

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. 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;
    }
  }
}
心的位置 2024-08-20 00:56:11

只是为了遍历,使用 const_iterators。如果要修改值,请使用迭代器。

例子:

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++;
}

Just to traverse, use 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++;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文