c++stdvectorstdinitializerlist

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

Solution

  • 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} {}