[英]How can I compare the first N elements of a std::set?
How can I compare first "n" elements of two sets are equal or not? 如何比较两组中的第一个“n”元素是否相等? My following program doesn't work, why?
我的以下程序不起作用,为什么?
#include <iostream>
#include <iterator>
#include <set>
#include<algorithm>
using namespace std;
int main ()
{
int n = 2;
int myints1[] = {75,23,65,42,13};
int myints2[] = {70,23,65,42,13};
set<int> myset1 (myints1,myints1+5);
set<int> myset2 (myints2,myints2+5);
if(std::equal(myset1.begin(),myset1.begin() + n ,myset2.begin())) //error
std::copy(std::myset1.begin(),myset1.begin() + n,ostream_iterator<int>(cout," ")); //error
cout << endl;
return 0;
}
UPDATE:
更新:
Is there a way to compare a specific element as well ? 有没有办法比较一个特定的元素? Thanks.
谢谢。
std::set iterators are bidirectional, not random-access. std :: set迭代器是双向的,而不是随机访问。 You can't say
begin() + n
with them. 你不能用它们说
begin() + n
。 Instead you might want to use std::advance
. 相反,您可能想要使用
std::advance
。
std::set<int>::iterator it(myset1.begin());
std::advance(it,n);
if(std::equal(myset1.begin(),it,myset2.begin()))
std::copy(myset1.begin(),it,ostream_iterator<int>(cout," "));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.