How to convert an "int" variable to vector iterator in C++?

  c++, iterator, static-cast, vector

Imagine two nested loops each iterating with integer variables (let’s say i and j). Inside these two loops, a function (fun) generates a vector (vec) using i and j as inputs. The generated vector has to be saved in a larger vector called total. I know that I can use push_back but I prefer to initialize my vector first (with static size). I tried to use insert but I don’t know how can I convert int to vector<int>::iterator. I tried static_cast<vector<int>::iterator>(2*i +j) but it gives me this error:

no suitable constructor exists to convert from "int" to "__gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int>>>"

vector<double> total(M, 0); // Initilized with zeros

for (int i = 0; i < A; ++i)
{
    for (int j = 0; j < B; ++j)
    {
        vector<double> vec = fun(i);                
        vecE.insert(static_cast<vector<int>::iterator>(2*i +j), vec.begin(), vec.end());
    }
}

Source: Windows Questions C++

LEAVE A COMMENT