Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change vector type using constructors?

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));
}
like image 351
Willem Avatar asked Jan 10 '19 15:01

Willem


People also ask

How do you pass a vector to a constructor?

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.

How do you initialize a vector in a class 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.

What happens if you use the default copy constructor for vector?

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.


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

like image 79
YSC Avatar answered Oct 09 '22 03:10

YSC