如何遍历 STL 集直到倒数第二个元素? [英] How to iterate through a STL set till the second last element?

查看:37
本文介绍了如何遍历 STL 集直到倒数第二个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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 :)

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

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)
{

}

推荐答案

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

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

这篇关于如何遍历 STL 集直到倒数第二个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆