I got terminate called after throwing an instance of 'std::bad_alloc'
when trying to push an additional string to a middle of a vector. I used g++ 4.8.2.
I even got output with wrong vector sizes size of str_vector 0: 1, size of str_vector 1: 1
when using g++ 5.2 on coliru.
The program works correctly when I use index (e.g., str_vector[0]
) to access vectors or use std::list
.
Does this mean there is some restriction on the use of iterator
? I assume that there should not any difference when I use index or iterator to access vectors.
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::string;
int main() {
vector<vector<string>> str_vector;
str_vector.emplace_back();
vector<vector<string>>::iterator it0 = std::prev(str_vector.end());
it0->push_back("a");
str_vector.emplace_back();
vector<vector<string>>::iterator it1 = std::prev(str_vector.end());
it1->push_back("a");
it0->push_back("a"); // bad alloc here
std::cerr << "size of str_vector 0: " << it0->size() << std::endl;
std::cerr << "size of str_vector 1: " << it1->size() << std::endl;
return 0;
}