简体   繁体   中英

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

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>>>"

using namespace std;
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);
        copy_n(vec.begin(), vec.size(), /* an iterator to where I want to save vec in total */);        
    }
}

The simplest method is vec.begin() + 2*i + j , but it'll work only for randomly accessible containers. For a generic solution you must use std::advance()

auto v = vec.begin();
std::advance(v, 2*i + j);

The return value of copy_n from the last iteration is the point where you should start inserting this iteration.

std::vector<double> total(M, 0); // Initilized with zeros
auto it = total.begin();

for (int i = 0; i < A; ++i)
{
    for (int j = 0; j < B; ++j)
    {
        auto vec = fun(i);
        it = std::copy_n(vec.begin(), vec.size(), it);
        // or it = std::copy(vec.begin(), vec.end(), it);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM