Change vector type using constructors?

Viewed 139

I have a vector full of integers. I have a class that takes an integer as a constructor. I want to create a new vector full of such class, using the values in the first vector as a constructor for each.

I have a feeling my current approach could be optimized greatly.

vector<int> integers = /*something...*/;

vector<clazz> clazzes();
for(auto& n : integers)
{
    clazzes.emplace_back(clazz(n));
}
2 Answers

There is a constructor of std::vector accepting a range and allowing user-defined conversion. This is what you need:

template< class InputIt >
vector( InputIt first, InputIt last, 
    const Allocator& alloc = Allocator() );

Full program:

#include <vector>
#include <iostream>

struct Wrapper
{
    int value;
    Wrapper(int n) : value(n) {}
};

int main()
{
    std::vector<int> integers = {0, 1};
    std::vector<Wrapper> wrapped{begin(integers), end(integers)};
    std::cout << wrapped[1].value << '\n';
}

Live demo

This is not particularly more optimized, but it makes less code so less bugs and less wtf/line. Which is good (TM).

What you have is reasonable (though see YSC's answer for a better approach). A simple improvement is to reserve the required storage, so that emplace_back() never needs to reallocate:

std::vector<clazz> clazzes;
clazzes.reserve(integers.size());  // <-- HERE
for(auto& n : integers)
{
    clazzes.emplace_back(clazz(n));
}
Related