简体   繁体   中英

How to place partially initialized struct object into a vector?

I currently have struct where I initialize only two of three member. I purposefully do this since during the time of creation I am not sure what the value will be ( I actually am fine with it being just zero).

struct my_data {
    my_data(int x_, int y_) {
       x = x_;
       y = y_;
    }


    int x;
    int y;
    double z = 0;
};

int main() {
   std::vector<my_data> my_vec;
   my_vec.resize(10);

   my_vec[0] = {3,4};
}

When I do this I get error: no matching function for call .... _T1(std::forward<Args ..

Is there any way to avoid this error or should I have to include z also in as parameter in constructor.

您需要一个默认的构造函数:

my_data() = default;

FWIW, you can make my_data easier to use by removing the constructor and the default value of z .

struct my_data {
    int x;
    int y;
    double z;
};

int main() {
   std::vector<my_data> my_vec;
   my_vec.resize(10);

   my_vec[0] = {};           // Same as = {0, 0, 0};
   my_vec[1] = {3};          // Same as = {3, 0, 0};
   my_vec[2] = {3, 4};       // Same as = {3, 4, 0};
   my_vec[3] = {3, 4, 2.0};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM