【问题标题】:How to iterate through a STL set till the second last element?如何遍历 STL 集直到倒数第二个元素?
【发布时间】:2017-06-06 19:24:23
【问题描述】:

我想遍历 STL 集合 以对集合中的元素成对 进行操作。例如。如果设置 S={1,2,3),我需要能够检查 {1,2},{2,3},{1,3}。

因此,一个非常错误的 C++ 代码如下-

set<bitset<2501> > arr;
unsigned sz = arr.size();

rep(i,sz-1)
{
    for(j=i+1;j<sz;j++)
    {
        //do processing and in my case is an OR operation
        if(((arr[i])|(arr[j])) == num)
        {
            cnt++;
        }
    }
}

我编写了上述错误代码是为了让您更好地了解我想要做什么。 更好的版本(应该有效但没有)如下-

set<bitset<2501> >::iterator secondlast = arr.end();
advance(secondlast,-1);

for(set<bitset<2501> >::iterator it1 = arr.begin();it1!=secondlast;++it1)
{
    for(set<bitset<2501> >::iterator it2 = it1+1;it2!=arr.end();++it2)
    {
        //do processing, I didn't show the OR operation 
    }
}

上面的代码给出了以下错误-

error: no match for 'operator+' in 'it1 + 1'|
error: no match for 'operator<' in '__x < __y'|

还有很多其他的注释,也有警告,但我认为主要的罪魁祸首是这两个错误。如果您需要整个剪贴板的错误,我稍后会根据您的要求进行编辑。

所以我可以请你解决错误并帮助我做我需要做的事情:)

编辑: 即使我从代码中删除了内部循环,我也会遇到错误。

set<bitset<2501> >::iterator secondlast = arr.end();
advance(secondlast,-1);

for(set<bitset<2501> >::iterator it1 = arr.begin();it1!=secondlast;++it1)
{

}

【问题讨论】:

  • 您可以使用std::next 而不是it1 + 1
  • @Jarod42 让我检查一次。
  • “比较”它们是什么? “检查”什么?
  • 您的标题和正文似乎不匹配
  • @BoundaryImposition 我在正文中将“比较”编辑为“执行操作”。确切地说,我想做 OR 操作。另外我认为正文确实提供了问题的详细信息。

标签: c++ stl c++03


【解决方案1】:

您正在使用operator+ 通过迭代器获取下一个元素,请改用预增量运算符std::advancestd::next

#include <iostream>
#include <iterator>
#include <set>

using std::cout;
using std::endl;

int main() {
    std::set<int> s{1, 2, 3, 4};

    for (std::set<int>::iterator i = s.begin(); i != s.end(); ++i) {
        for (std::set<int>::iterator j = std::next(i); j != s.end(); ++j) {
            cout << *i << " and " << *j << endl;
        }
    }
}

【讨论】:

  • 其实我使用的是 C++ 4.3.2。所以 auto 不存在。
  • @Quentin 之前从其他东西遗留下来的...应该删除它
  • 我不知道这将如何到达 (2,3)
【解决方案2】:

您可以在 C++11 中使用以下内容:

std::set<std::bitset<2501>> arr;
std::set<std::bitset<2501>>::iterator end= arr.end();

for(std::set<std::bitset<2501> >::iterator it1 = arr.begin();it1 != end; ++it1)
{
    for(std::set<std::bitset<2501> >::iterator it2 = std::next(it1); it2 != end; ++it2)
    {
        //do processing, I didn't show the OR operation 
    }
}

【讨论】:

  • 你能告诉我如何处理这个新错误
  • @iammangod96 升级您的编译器,以便您至少可以使用 C++11。同时,我在您的问题中添加了 [c++03] 标签(对不起 Jarod!)
猜你喜欢
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
相关资源
最近更新 更多