Humam Helfawi
Humam Helfawi

Reputation: 20274

std::tuple vs std::array as items of a std::vector

I have this case:

std::vector<4_integers> v;

What would fit best here?

std::tuple solution:

std::vector<std::tuple<int,int,int,int>> v;

std::array solution:

std::vector<std::array<int,4>> v;

and why?

EDIT (The use case):

Sorry for not mentioning that before. I am going to use it as follow:

for(const auto& item:v){
   some_function(item[0],item[1],item[2],item[3]); // or tuple equivalent 
}

Of course I need to keep them stored because computing the 4 integers is not a thing that I want to repeat again and again.

Upvotes: 12

Views: 9927

Answers (2)

Ari Hietanen
Ari Hietanen

Reputation: 1769

This depends a lot on the use case, but if the elements are somehow related, I would choose array. You can iterate over array and use std algorithms with them.

I usually think tuple as a substitute to something you could replace with a struct like:

struct fourIntegers{
  int int1;
  int int2;
  int int3;
  int int4;
};

Sometimes the tuple is just more compact/clear than a new struct.

Upvotes: 4

Ami Tavory
Ami Tavory

Reputation: 76297

For this specific case, I'd have to disagree with the comments. For homogeneous type containers - as is the case here (all ints) - array is superior.

When looking at the interface of std::tuple vs. std::array, it is very clear that the latter is a container (with iterators, e.g.), while the former is not. This means that the rest of the standard library will be much more naturally applicable to the latter.

If the types weren't homogeneous, there wouldn't be a question - it would have to be std::tuple.

Upvotes: 12

Related Questions