简体   繁体   中英

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? 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. You can't say begin() + n with them. Instead you might want to use 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," "));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM