Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

9.22: Iterator mid is invalidated any time an insertion before it occurs #34

Open
xjay73 opened this issue Jun 27, 2021 · 0 comments
Open

Comments

@xjay73
Copy link

xjay73 commented Jun 27, 2021

The program also has an error in that the location of mid must be handled some other way, as the iterator to mid would be invalidated every time an insertion in the front half of the vector occurs -- though this program doesn't do it, it could be invalidated after any operation that changes the size of the container.

One way to handle this would be removing the need to access the mid iterator any time after the loop starts:

std::vector<int>::iterator iter = iv.begin();

for (std::vector<int>::size_type cnt = iv.size()/2; cnt != 0; --cnt) {
  if (*iter == some_val) {
    iter = iv.insert(iter, 2 * some_val);
    ++iter;
  }
  ++iter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant