Auto resize std::vector when I use insert

What is elegant way to insert an element to particular position of std::vector ? If std::vector has size less than a position.

For example:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> vec(8);
    vec.insert(vec.begin() + 200, 5); // fail, I need auto-resize
}

1 answer

  • answered 2017-11-14 23:18 Fureeish

    Use std::vector::resize, with appropriate argument. Say you have your:

    std::vector<int> vec(8);
    

    Simply use:

    vec.resize(201);
    vec.insert(vec.begin() + 200, 5);
    

    You could also wrap it around your own template function, which could check for possibly needed allocation:

    template<class T>
    void safe_insert(std::vector<T>& vec, const size_t pos, const T arg)
    {
        if(vec.size() <= pos) vec.resize(pos);
        vec.insert(vec.begin() + pos, arg);
    }
    

    Calling it like so:

    std::vector<int> vec(8);
    safe_insert(vec, 200, 5);
    std::cout << vec[200];
    

    The code outputs: 5.