How to iterate through a STL set till the second last element?

这一生的挚爱 提交于 2021-01-28 08:11:19

问题


I want to iterate through a STL set to do operations on elements pairwise in the set. For eg. if set S={1,2,3), I need to be able to check {1,2},{2,3},{1,3}.

So a very wrong C++ code for this would be as follows-

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

I wrote the above wrong code to give you a better idea of what I want to do. A better version (should have worked but did not) is as follows-

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

The above code is giving the following errors-

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

There were a lot of other notes, warnings also but I think the main culprits are these two errors. If you require the whole clipboard of errors, I'll edit it later on your say.

So I can you please solve the errors and help me do what I need to do :)

EDIT: Even if I remove the inner loop from the code then also I'm getting errors.

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

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

}

回答1:


You may use the following in 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 
    }
}



回答2:


You are using operator+ to get the next element through an iterator, use the preincrement operator, std::advance or std::next instead

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


来源:https://stackoverflow.com/questions/44398264/how-to-iterate-through-a-stl-set-till-the-second-last-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!