+ 4

# what does end() do in <set>? [SOLVED]

In the following code end() prints the no. Of elements in the set and not the last element but according to geeksforgeeks end() - Returns an iterator to the theoretical element that follows last element in the set. What does that mean? I thought it would print the last element in the set https://code.sololearn.com/cmtW1Yii3UdT/?ref=app

2nd Jul 2019, 3:18 PM
Saurabh Tiwari
7 Antworten
+ 4
end() returns an iterator that points to the first element *after* the container (e.g a set) http://www.cplusplus.com/reference/iterator/end/
2nd Jul 2019, 3:39 PM
daniel
+ 3
daniel just like in array, in this case 33 corresponds to the 4th index value so *a.end() prints the next index value that is 5 am i correct?
2nd Jul 2019, 3:47 PM
Saurabh Tiwari
+ 3
Not exactly. Sets dont have indexes by any manner. It returns an iterator (kind of a pointer) to the element that is after the last element. By coincidence that may point to the place that the set.size() is stored.
2nd Jul 2019, 4:09 PM
daniel
+ 3
Saurabh Tiwari thats exactly what i ment. You accessed the place the set.size() is stored (And not a garbage value). It makes sense that the size is stored right after the set itself.
2nd Jul 2019, 4:19 PM
daniel
+ 2
*a.end() is undefined behaviour. It's the same as if you had an array with 5 elements and tried to do array[5]. In this case the memory layout for std::set<int> is something like: 10 6D 79 00 00 00 00 00 00 00 00 00 00 00 00 00 A0 6D 79 00 00 00 00 00 00 6E 79 00 00 00 00 00 30 6E 79 00 00 00 00 00 05 00 00 00 00 00 00 00 The last part 05 00 00 00 00 00 00 00 is the variable that holds the size of the set. *a.end() just happens to access that variable. I could edit this to an 8 for example and *a.end() and a.size() will print an 8. unsigned char* ptr = reinterpret_cast<unsigned char*>( &a ); // where a is the set ptr[40] = 8; But the layout could be different depending on compiler.
2nd Jul 2019, 4:03 PM
Dennis
+ 2
Dennis whoa!!! that was some next level stuff every single word went above my head *feels demotivated
2nd Jul 2019, 4:09 PM
Saurabh Tiwari
+ 2
daniel no. i dont think it is a coincidence try changing the no. of elements it always prints the no. of elements
2nd Jul 2019, 4:11 PM
Saurabh Tiwari