set container

Hi all,

let us consider this example on cplusplus

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// set::begin/end
#include <iostream>
#include <set>
using namespace std;

int main ()
{
  int myints[] = {75,23,65,42,13};
  set<int> myset (myints,myints+5);

  set<int>::iterator it;

  cout << "myset contains:";
  for ( it=myset.begin() ; it != myset.end(); it++ )
    cout << " " << *it;

  cout << endl;

  return 0;
}



my question is how can i compare the iterator it with the address of the last element of myset?
i have triad as the following:

1
2
3
4
5

if(it == myset.end()-1) // error. how could this syntax written correct?
{
 // something
}


thanks
Last edited on
it != myset.end()

=>

it == myset.end()
- operator only works with random access iterators. set does not have random access iterators.

Next best thing you can do is the -- operator:

1
2
3
4
5
6
set<int>::iterator lastelement = myset.end();
--lastelement;

for( ... )
{
  if(it == lastelement)


EDIT:

@Incubbus:

His loop is fine. != is the right operator to use there
Last edited on
*it == it.back()

assuming the set isn't empty, since set does not allow duplicates.
Last edited on
1
2
3
4
if(it == myset.end()-1) // error. how could this syntax written correct?
{
 // something
}



1
2
3
4
if(it == (++myset.rbegin()).base())
{
 // something
}


By getting the base of incremented reverse iterator.
That's convoluted.
Topic archived. No new replies allowed.