如何比较std :: set的前N个元素?

时间:2011-03-09 01:41:02

标签: c++ iterator set

如何比较两组中的第一个“n”元素是否相等?我的以下程序不起作用,为什么?

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

更新:

有没有办法比较特定元素? 感谢。

1 个答案:

答案 0 :(得分:8)

std :: set迭代器是双向的,而不是随机访问。你不能跟他们说begin() + n。相反,您可能希望使用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," "));