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));
}
Begin Declare a class named as vector. Declare vec of vector type. Declare a constructor of vector class. Pass a vector object v as a parameter to the constructor.
You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.
The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With