Change vector type using constructors?

  • A+

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)); } 


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).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: