What is the efficient way to populate vector from vector of vector?

I have a vector of vector like std::vector< std::vector< int> > and from this vector I want to populate std::vector< int>, can you please tell me efficient way to do this? There might be some boost feature which I can use. I am using VS2010. Below code snippet is what I tried:

std::vector<std::vector<int> >::iterator outereItr = vecOfVec.begin();

while(outereItr != vecOfVec.end()) 
{
    std::vector<int>::iterator innerItr1 = (*outereItr).begin();
    while(innerItr1 != (*outereItr).end())
    {
        masterVec.push_back(*innerItr1);
        ++innerItr1;
    }
    ++outereItr;
}

Answers


You can use insert to insert a whole vector, rather than each element individually. This will probably reduce the number of reallocations.

for (auto const & vec : vecOfVec) {
    masterVec.insert(masterVec.end(), vec.begin(), vec.end());
}

or, if your compiler doesn't support new-style for loops and type deduction

for (std::vector<std::vector<int> >::iterator it = vecOfVec.begin(); it != vecOfVec.end(); ++it) {
    masterVec.insert(masterVec.end(), it->begin(), it->end());
}

It might (or might not) be more efficient to add up the size of all the vectors, then reserve enough space in masterVec before you start.


You can use the function std::vector::insert.

std::vector<int> masterVec;
for(std::vector<std::vector<int> >::iterator it=vecOfVec.begin(); it!=vecOfVec.end(); ++it) {
    masterVec.insert(masterVec.end(), it->begin(), it->end());
}

If you can use C++11 the code will be much cleaner:

std::vector<int> masterVec;
for(const auto& x : vecOfVec) {
    masterVec.insert(masterVec.end(), x.begin(), x.end());
}

As Kiril pointed out in the comments computing the size of the result vector first is a good idea to avoid reallocation:

size_t size = 0;
for(std::vector<std::vector<int> >::iterator it=vecOfVec.begin(); it!=vecOfVec.end(); ++it) {
    size += it->size();
}
std::vector<int> masterVec;
masterVec.reserve(size);
for(std::vector<std::vector<int> >::iterator it=vecOfVec.begin(); it!=vecOfVec.end(); ++it) {
    masterVec.insert(masterVec.end(), it->begin(), it->end());
}

Need Your Help

Chrome extension is grey and popup won't show

javascript html google-chrome-extension

My Chrome extension is grey and the popup won't show. I am trying to get it to work on "https://scratch.mit.edu" and all subdomains, but it is grey on every site. The popup also doesn't show on any...

BufferedReader not iterating properly

java file-io bufferedreader

I'm running into a weird bug I've never seen before in Java. I have a BufferedReader which I'm using to read from a .txt file. I'm trying to grab some text from a few of the lines in my text file