Reputation: 1167
I have a c++ class that is contained as a vector of objects in another class.
class Small
{
public:
int a;
int b;
int c;
};
class Big
{
public:
vector< Small > getSmallVec() const { return m_smallVec;}
private:
vector< Small > m_smallVec;
};
I'd like to be able to access the members of the Small class as a vector themselves. In other words, I'd like to have a function in Big like
vector<int> getSmallVec_a()
which would return a vector that contains each value of int Small::a in m_smallVec. The only way I can think of doing it would be to iterate over m_smallVec and copy to a vector of int. Is there a way to do this without copying?
Upvotes: 2
Views: 530
Reputation: 3411
there is no way to do that without seperating small components in diffrent vectors since a vector is just working as an array that means when you are creating a vector of smalls there will be 2 blocks space between small::a variables whereas what you what to return is just an array of ints. and by the way it's much more efficient if you delcere you function as vector <int> & getSmall()
since if you don't return a refrence it'll cause a copying m_smallVec and returning it as the result, it also makes it impossible to change any value in m_smallVec.
Upvotes: 0
Reputation: 65599
If this is how you expect to access data and performance is important, have you considered using parallel vectors? Instead of
std::vector<Small>
In "Big" you actually maintain 3 vectors
std::vector<int> aVec;
std::vector<int> bVec;
std::vector<int> cVec;
All elements at 0 correspond to the 0'th "Small", and you can easily seperate out all the as from the bs.
This comes a lot of annoying bookkeeping that you'd be have to be sure to get right and encapsulate well. Its not a more elegant solution, I usually dislike this kind of thing and would probably question in a code review, but it would probably give you the best performance for the operations you've described.
Upvotes: 2