Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding empty element to declared container without declaring type of element

Tags:

c++

c++11

When we use a complicated container in C++, like

std::vector<std::map<std::string, std::set<std::string>>> table;

The only way to add an empty map (which may represent a row or column) is to initialize a new element and push it back. For example with

table.push_back(std::map<std::string, std::set<std::string>>());

Is there any way to avoid redeclaring the type, and just adding the correct typed element?

like image 398
Vineet Avatar asked Mar 25 '19 06:03

Vineet


4 Answers

From CLion's IntelliSense, I later found that one useful method is emplace_back(). This constructs a new object of correct type and adds it to the end of the vector.

table.emplace_back();
like image 136
Vineet Avatar answered Oct 07 '22 02:10

Vineet


You can take advantage of copy-list-initialization (since C++11) and just write

table.push_back({});
like image 26
songyuanyao Avatar answered Oct 07 '22 02:10

songyuanyao


Before C++11 sometimes I use x.resize(x.size()+1), in C++11 or later you can use x.push_back({}).

like image 10
6502 Avatar answered Oct 07 '22 00:10

6502


Though the other answers are correct, I will add that if you couldn't take that approach, you could have benefitted from declaring some type aliases to shorten that container type name.

I can of course only guess at the logical meaning of your containers, which is another thing that this fixes!

 using PhilosopherNameType = std::string;
 using NeighboursType      = std::set<PhilosopherNameType>;
 using NeighbourMapType    = std::map<PhilosopherNameType, NeighboursType>;

 std::vector<NeighbourMapType> table;
 table.push_back(NeighbourMapType());

I mention this because you can likely still benefit from this in other places.

like image 5
Lightness Races in Orbit Avatar answered Oct 07 '22 00:10

Lightness Races in Orbit