I have a std::list
that I am inserting items into, and I have a std::unordered_map
where I want to store iterators to the elements inserted into the std::list
(I am implementing a LRU cache). The following code does not give me the output I expect:
#include <list>
#include <unordered_map>
#include <iostream>
int main()
{
std::list<int> l;
std::unordered_map<int, std::list<int>::iterator> listItems;
for (int i = 0; i < 5; i++)
{
l.push_back(i);
listItems[i] = std::end(l);
}
for (int i = 0; i < 5; i++)
std::cout << *(listItems[i]) << " ";
std::cout << std::endl;
}
The output here is 5 5 5 5 5
- the output I want/expect is 0 1 2 3 4
. I would have guessed looking at this code that std::end
returns an iterator to the last element of the list, which is copied into listItems[i], but this is clearly not what is happening. I am confused why adding items to the list affects the result of earlier calls to std::end
However, if I change the first loop to
for (int i = 0; i < 5; i++)
{
l.push_front(i);
listItems[i] = std::begin(l);
}
I get the output I expect - 0 1 2 3 4
. So what is the difference here between push_front
and push_back
, and std::begin
and std::end