How to initialize a vector / array using an enumeration?

I am wondering if there is a way to initialize a vector using an enumeration. Enumeration is necessary because I create a vector of objects (the same class, Chess_piece, but of a different type). I want to have access to an element without a lot of tests ( if (this is white pawn 8)... ). Enumeration can be used to drill down the shapes in the beautiful way vec(W_PAWN8)... Anyway, when I create a vector, I do something like this (pseudo code)

 //generate enum of pieces enum pieceList{ ... } pieceEnum; vector<int> pieceIter = {W_PAWN1,W_PAWN2,...}; //equal to {1,2,...} //board index goes from lower left to upper right vector<int> boardIdx = {8,9,10,11,12,13,14,15,16,1...}; vector<Piece*> pieceVec; for (int i=0; i<32; i++) pieceVec.pushback( new Piece( boardIdx(i), pieceIter(i) ) ); 

However, now I actually write the same thing 2 times. And when I create the listing and pieceIter . For this program, I can live with it, but I may have the same problem more than once.

That's why I wonder if something like vector<int> pieceIter {pieceEnum}; in c ++? Of course, the code snippet in the previous sentence is not valid, but I think it hints at my problem, use all the variables in the enumeration and initialize the vector in a simple way?

If not, is it possible to use some "range initialization" for a vector, for example, in matlabl. Sort of:

 vector<int> vec {1:32}; 

But with C ++ syntax?

+5
source share
2 answers

So, if you want to generate a range from 1 to 32, you can use generate for this, combined with lambda.

 #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v(32); int n=0; std::generate(v.begin(), v.end(), [&]{ return ++n; }); //to display the results for (auto& it: v){ cout<<it<<" "; } return 0; } 

Conclusion: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

Hope that helps

+3
source

One way to resolve this issue is to add a value to the enumeration, which is always the last. Then you can fill the vector by going to the value. Something like that:

 enum VALUES{ VALUES_FIRST = 0, VALUES_SECOND, VALUES_END }; std::vector<VALUES> Allvalues; for(int i = 0; i < VALUES_END; i++){ Allvalues.push_back(static_cast<VALUES>(i)); } 

Fills the vector with all the values ​​in the enumeration (not counting the last value of the marker), if you do not put anything after VALUES_END .

+1
source

Source: https://habr.com/ru/post/1209387/


All Articles