Are all end () iterators equivalent for the collection type?

Given a specific stl collection in C ++, is the value equivalent end()for all instances of the same templatization? In other words, will the following work for all stl containers and conditions (and not just for std :: map)?

std::map<Key, Value> foo(int seed);

std::map<Key, Value> instance1 = foo(1);
std::map<Key, Value> instance2 = foo(2);
std::map<Key, Value>::iterator itr = instance1.begin();
std::map<Key, Value>::iterator endItr = instance2.end(); // Comes from other collection!

for (; itr != endItr; ++itr) {
  // Do something on each key value pair...
}
+5
source share
3 answers

No, due to the requirements of the STL container and iterator:

23.2.1 General requirements for containers [container.requirements.general]

6 begin () returns an iterator referring to the first element in the container. end () returns an iterator, which is the value of the end of the past for the container. If the container is empty, then begin () == end ();

24.2.1 General [iterator.requirements.general]

6 j , ++ i, == j. j i, .

begin() end() , begin() end() , , , end() . , - , operator-- end(), end().

+6

, , . .

, , istream_iterator:

ifstream a("foo.txt");
ifstream b("bar.txt");
istream_iterator<string> end;
istream_iterator<string> ia( a);
istream_iterator<string> ib( b);
// from here on both [ia, end> and [ib, end> are valid ranges.
+2

:

#include <map>
#include <iostream>
using namespace std;
map<int,int> m1;
map<int,int> m2;

int main() {
  cout<<(m1.end() == m2.end())<<endl;
}

http://ideone.com/o18DtQ

:

0
0

All Articles