Junior — Senior
Checking iterator validity after container modification
livecode
Task condition
It is necessary to analyze how safe it is to use the obtained iterator after new elements are added to the container, and to specify for which STL containers such usage does not lead to invalidation.
template<typename T>
void impl(T& data) {
data.push_back(0);
auto iterator = data.begin();
for (size_t i = 1u; i < 1000u; ++i) {
data.push_back(i);
}
std::cout << "First: " << *iterator << std::endl;
}
int main(int argc, char** argv) {
std::list<int> data_1;
impl(data_1); // safe
std::vector<int> data_2;
impl(data_2); // iterator invalidates on push_back
return EXIT_SUCCESS;
}