Reputation:
I'm attempting to use an std::vector
in c++, specifically one of type std::string
. However, the iterator is acting strangely when I attempt to insert elements into the std::vector
and print them out.
The following code simply prints "Segmentation Fault":
std::vector<std::string> request;
auto it = request.begin();
request.insert(it, "foo");
request.insert(++it, "bar");
std::cout << request.front() + "\n";
The code also prints "Segmentation Fault" when I leave the iterator as is, i.e. if I do not try to increment it. If I comment out the line inserting "bar" into the code, i.e. without the it
increment (++it
), the code prints "foo". In addition, I can add "bar" using request.begin()
or request.end()
and it prints the right thing ("bar" or "foo" respectively). I'm asking this here because this behavior does not match up with the behavior displayed in the tutorial for std::vector.insert()
given on cplusplus.com, nor does it seem to match with any other examples on line, and I can't seem to figure out why it prints "Segmentation Fault" which I would assume would occur if you were to try to print a non-existing element, or at least that's what happened when I tested this theory on an empty vector.
Upvotes: 0
Views: 98
Reputation: 206567
The problem is that it
is not required to be a valid iterator after
request.insert(it, "foo");
Hence, using ++it
in the next line, as
request.insert(++it, "bar");
is cause for undefined behavior.
You may use
it = request.insert(it, "foo");
request.insert(++it, "bar");
Upvotes: 4