Home > Blockchain >  Iterate over a vector and create another vector based on elements
Iterate over a vector and create another vector based on elements

Time:03-20

Maybe a stupid/naive question, but if I have a vector of vectors like this:

std::vector<std::vector<Element> vec

what is the most efficient way to create another vector from this one which containes all the sizes of elements from the previous vector:

std::vector<std::size_t> newVector = {vec[0].size(), ..., vec[vec.size()-1].size()}

is there a function for stuff like this?

Thanks in advance.

CodePudding user response:

There might be a 1-liner approach using something from <algorithm> or fancy accumlator/transform routine. But it's hard to beat the readability of this:

std::vector<std::size_t> newVector;
for (const auto& item : vec) {
    newVector.push_back(item.size());
}

If you prefer the hip way to do it, which some people like, but in my opinion makes for rather unreadable code.

vector<int> newVec(vec.size());
std::transform(vec.begin(), vec.end(), newVec.begin(), [](vector<int>& v) {return v.size(); });
  • Related