Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Container initialization in C++98

Tags:

c++

stl

c++98

I have to construct an ordered container (which must be iterable) with the following rule:

If the condition is true, the container is {1,0}, else it's {0,1}

I have the following code, but I don't find it "elegant":

   vector<int> orderedSides;
   if (condition) 
   {
       orderedSides.push_back(1);
       orderedSides.push_back(0);
   }
   else            
   {
       orderedSides.push_back(0);
       orderedSides.push_back(1);
   }

Is there a better way to do this (from concision and performance point of view)?

like image 775
youyou Avatar asked Jun 30 '17 07:06

youyou


3 Answers

You might implement something like this:

vector<int> orderedSides(2, 0);
(condition ? orderedSides.front() : orderedSides.back()) = 1;

which is a little bit shorter than explicit if clauses.

As @Deduplicator mentioned below, we might rewrite the second line in a more concise way:

orderedSides[!condition] = 1;
like image 58
Edgar Rokjān Avatar answered Oct 11 '22 05:10

Edgar Rokjān


vector<int> orderedSides;
orderedSides.push_back(condition ? 1 : 0);
orderedSides.push_back(condition ? 0 : 1);

I don't think it's more performant but I find it more elegant.

like image 28
Antoine Thiry Avatar answered Oct 11 '22 05:10

Antoine Thiry


You could compromise between efficiency and avoiding repetition, initialise the first with the condition and the second from the first.

vector<int> orderedSides(1, bool(condition)) ;
orderedSides.push_back(!orderedSides.back());
like image 20
Mic Avatar answered Oct 11 '22 06:10

Mic