简体   繁体   中英

In place creation of custom type object in std::list

Let's say I have a struct

struct someStruct
{
    int a;
    customType b;
};

and an std::list of someStruct instances

std::list<someStruct> aList;

One way of storing items to that list is by creating an instance of someStruct , store the values I want to that instance and then store the instance in the list like that

someStruct obj;
obj.a = 4;
obj.b = customType::value_type;
aList.push_back(obj);

Is there a more generic way of doing this so that I don't need to create an object?

Sorry for using an array as example at first!

In C++11 you can do

anArray[0] = {123, 456};

Or more verbosely:

anArray[0] = someStruct{123, 456};

And in any version of C++ you can perform aggregate array initialization:

someStruct anArray[10] = {{1, 2}, {3, 4}, /*...*/};

Edited because the original question changed:

Since this is now explicitly C++, the one-liner way to do this is to provide a constructor for the struct.

struct someStruct {
  someStruct(int new_a, customType new_b) : a(new_a), b(new_b) {}
  int a;
  customType b;
};

...

aList.push_back(someStruct(4, customType::value_type));

This is closely related to push_back() a struct into a vector

In C you can use the designated initializer syntax:

struct someStruct ss[] = {
    {.a=5, .b=6}
,   {.a=6, .b=7}
,   {.a=7, .b=8}
};

Demo.

This syntax is not available in C++, so you have to stick to the old-style initialization based on positions:

struct someStruct ss[] = {
    {5, 6}
,   {6, 7}
,   {7, 8}
};

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