Edit: I'm changing 1st to lst
I'm still learning about insert on C .
why use iter =
here?
list<string> lst;
auto iter = lst.begin();
while (cin >> word)
iter = lst.insert(iter, word);
why not like this?
list<string> lst;
auto iter = lst.begin();
while (cin >> word)
lst.insert(iter, word);
I'm confused because there is also this case, which don't use slist.begin() =
list<string> slist;
slist.insert(slist.begin(), "Hello!");
CodePudding user response:
The difference becomes immediately apparent when you look at the output of the following for input:
1
2
3
A:
#include <list>
#include <iostream>
using namespace std;
int main()
{
std::list<std::string> st;
auto iter = st.end();
std::string word;
while (cin >> word)
iter = st.insert(iter, word);
for (const auto& w : st) std::cout << w << " ";
}
output:
3 2 1
B:
#include <list>
#include <iostream>
using namespace std;
int main()
{
std::list<std::string> st;
auto iter = st.end();
std::string word;
while (cin >> word)
st.insert(iter, word);
for (const auto& w : st) std::cout << w << " ";
}
output:
1 2 3
Note that I used end()
instead of begin()
, because begin()
looks a little fishy when there is no element yet in the list. However, for an empty list begin() == end()
so it does not change the result.
std::list::insert
inserts the element before the one referenced by the iterator you pass and returns an iterator to the newly inserted element. Hence, A inserts the next element always before the last one that was inserted. On the other hand, B always inserts the next element at the end, because iter
always points to the lists end
.