-1

I am learning to use stl vector and It is odd that this program cannot work. What is wrong with it? How should I do if I want to implement the same function with vector?

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<int> vec;
    vector<int>::iterator it;
    vector<int>::iterator temp;
    it = vec.begin();
    vec.insert(it, -1);
    it++;
    vec.insert(it, 2);
    for(temp = vec.begin();temp!=vec.end();temp++)
        cout<<*temp<<' ';
    return 0;
}
  • 3
    What is not working for you? We are no wizards who can guess what you get and what you expect from your code – RoQuOTriX Mar 24 '21 at 13:12
  • 6
    [`insert`](https://en.cppreference.com/w/cpp/container/vector/insert) will invalidate all iterators if reallocation should be needed. You should never rely on iterators after changing operations in vector. – Yksisarvinen Mar 24 '21 at 13:12
  • 1
    Don't predeclare variables in c++. And using `auto` for iterators is so much easier (and more readable) – JHBonarius Mar 24 '21 at 13:14
  • 1
    why do you think there is something wrong? When you get an compiler error please include it in the question. When output is not what you expected, please tell us what you expected and what you got instead – 463035818_is_not_a_number Mar 24 '21 at 13:15
  • @JHBonarius _"Don't predeclare variables in c++"_... Why ? There are plenty of cases where it is necessary, there's nothing wrong with that. – Fareanor Mar 24 '21 at 13:24
  • @Fareanor "plenty of cases"? The *one* case where it can't be avoided is initialising an object from an `istream` – Caleth Mar 24 '21 at 13:26
  • @Caleth Yes, that was that kind of cases that I had in mind (a container that needs to be filled later,from a file, another thread, etc...) – Fareanor Mar 24 '21 at 13:29
  • 4
    it seems that `vector::push_back()` is what you need. – anastaciu Mar 24 '21 at 13:30
  • @Fareanor because it's not C. [C++ Core guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-init) – JHBonarius Mar 24 '21 at 14:12
  • @JHBonarius In this case, of course, this is useless ! But I was just noticing that there's nothing wrong with predeclaring a variable (and sometimes, you cannot avoid it). What would be wrong is to **access an uninitialized** variable, hence this guideline. So in my opinion, your warning would better be either _"Don't predeclare variables/let them uninitialized **if you can avoid it**"_ or _"Be careful to never access uninitialized variables"_. – Fareanor Mar 24 '21 at 14:22
  • @Fareanor IMHO you're overgeneralizing my comment... – JHBonarius Mar 24 '21 at 15:19
  • @JHBonarius Ahah no pb, I understood you from the very beginning. I've just told this to make sure OP understand why you said that, the real reason behind, not that this is bad (indeed the program is well-formed) but what bad things can be possible by doing that. Sorry if I wasn't clear. – Fareanor Mar 24 '21 at 15:23

2 Answers2

7

vec.insert(it, -1); invalidates it.

You should rather use it = vec.insert(it, -1); which will keep it valid.

You can see the documentation:

https://en.cppreference.com/w/cpp/container/vector

section called "Iterator invalidation" or look at this great question and answer: Iterator invalidation rules

Jeffrey
  • 7,814
  • 1
  • 16
  • 32
  • 1
    [Aggregation and plain English list of all iterator invalidation rules for all Standard Library containers.](https://stackoverflow.com/questions/6438086/iterator-invalidation-rules) – user4581301 Mar 24 '21 at 14:33
-7

On executing the code

vector<int> vec;

You created an object named vec, it has no elements and vec.size() will be zero.

So what vec.begin() returns is the same as what vec.end() returns.

By doing vec.insert(it, -1); you are inserting a value out of vec's range. That is undefined behavior.

No, vec.insert(it, -1) works well, but vec.insert(it, -1) causes the vector to reallocate memory for its first element.

That invalids it.

Try vec.emplace_back(-1) or vec.resize(2) instead. They extend vec's size and capacity.

aleck099
  • 39
  • 4
  • 4
    "By doing `vec.insert(it, -1);` you are inserting a value out of `vec`'s range." Why? As explained in the [documentation](https://en.cppreference.com/w/cpp/container/vector/insert) of the `pos` argument: "_iterator before which the content will be inserted. **pos may be the end() iterator**_" (emphasis - mine). – Algirdas Preidžius Mar 24 '21 at 13:30