Eden Cheung
Eden Cheung

Reputation: 333

how to assign std::initializer_list to a vector

This is a constructor which requires an std::initializer_list and I want to assign it to a vector. Do I need to use a for-loop to assign each item in the std::initializer_list to the vector one by one?

Motor_Group::Motor_Group(std::initializer_list<pros::Motor> port_set)
{
  this->motor_vector = port_set;
}

Upvotes: 3

Views: 5289

Answers (2)

lubgr
lubgr

Reputation: 38295

Do i need to use a for loop [...]?

No. In order to initialize Motor_Group::motor_vector of type std::vector<pros::Motor>, you should use the member initializer list of the constructor Motor::Group:

Motor_Group::Motor_Group(std::initializer_list<pros::Motor> port_set) :
    motor_vector{port_set}
{}

Initialization should be preferred over assignment in constructor bodies, as it results in an unnecessary invocation of the data member's default constructor first. This isn't necessarily a measurable performance penalty (it could be, in rare cases, though), but a control flow that requires more thoughts than plain initialization.

Upvotes: 7

Yuri Feldman
Yuri Feldman

Reputation: 2584

Try

this->motor_vector = std::vector{port_set}; 

or better, use the initialization list:

Motor_Group::Motor_Group(std::initializer_list<pros::Motor> port_set)
    : motor_vector{port_set} {}

Upvotes: 6

Related Questions