pokche pokche - 3 months ago 25
C++ Question

How to return vector of enum outside the class?

Lets say A class has 2d vector of enum and I want to access this 2d vector outside of the class and manipulate the value.

My Question is : How can I declare the new vector to hold the return by value outside of the class, since my type ( enum type) is inside the class? I was hoping to some thing like

A a(5);
std::vector<std::vector<A::s> > x = a.get_2dvec();


But this give me error saying its private and then if I make type public I get not declared error.

I know I could place enum s {RED, BLUE, GREEN}; and typedef s color; outside of class and achieve the result but lets say the main is on different file.

// f1.cpp

#include <iostream>
#include <vector>

class A{
// This enum is inside class
enum s {RED, BLUE, GREEN};
typedef s color;
const int size = 3;
std::vector<std::vector<color> > color_array;
public:
A(int size_):size(size_),color_array(size){
std::cout << "vector size = " << color_array.size() << std::endl;
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
color_array[i].push_back(RED);
}
}
}
void print(){
for(auto it = color_array.begin(); it != color_array.end(); it++){
for(auto itt = it->begin(); itt != it->end(); itt++){
std::cout << *itt << " : " << std::endl;
}
}
}

// pass vector by value
std::vector<std::vector<color> > get_2dvec(){
return color_array;
}
};

// main.cpp
int main(){
A a(4);
a.print();
// here I some how need to capture the 2d enum vector
std::vector<std::vector<enum-type> > x = get_2dvec();



return 0;
}

Answer

get_2dvec() is a member function, which needs an object to call on it. And if you don't want to make A::s public, you could use auto specifier (since C++11) to avoid accessing private name directly. (But I'm not sure whether this is what you want.)

Change

std::vector<std::vector<enum-type> > x = get_2dvec();

to

auto x = a.get_2dvec();