Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize vector/array using an enum?

Tags:

c++

enums

vector

I am wondering if there are some way to initialize a vector using an enum. The enum is necessary because I am creating a vector of objects (same class, Chess_piece, but different type). I want to be able to access the element without a lot of tests (if (this is white pawn 8)...). The enum can be used to itemize the pieces in a nice way vec(W_PAWN8).... Anyway when I create 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. Both when I create the enum and pieceIter. For this program I can live with it, but I may have the same issue more than once.

This is why I wonder, does it exist something like vector<int> pieceIter {pieceEnum}; in c++? The code snippet in the previous sentence is invalid of course, but I think it hints my problem, to use all variables in the enum and initialize the vector in a simple way?

If not, is it possible to use some kind of "range initialization" for vector like in matlabl Something like:

vector<int> vec {1:32};

But with c++ syntax?

like image 242
patrik Avatar asked Dec 17 '14 18:12

patrik


2 Answers

So if you want to generate a range from 1 to 32 you can use generate to do that, combined with a 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;
}

Output: 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

like image 111
Gabriel Avatar answered Oct 05 '22 05:10

Gabriel


One way to solve this would be adding a value to the enum that is always the last one. Then you could fill the vector by looping up to the value. Something like this:

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));
}

Would fill the vector with all the values in the enum (not including the last marker value) as long as you don't put anything after VALUES_END.

like image 32
Henri Hyyryläinen Avatar answered Oct 04 '22 05:10

Henri Hyyryläinen