Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 420
Humam Helfawi Avatar asked Mar 02 '16 09:03

Humam Helfawi


People also ask

Is STD array faster than vector?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

What is the difference between std :: array and std::vector?

Difference between std::vector and std::array in C++Vector is a sequential container to store elements and not index based. Array stores a fixed-size sequential collection of elements of the same type and it is index based. Vector is dynamic in nature so, size increases with insertion of elements.

Which is better array or vector?

Arrays cannot be returned unless dynamically allocated from a function whereas vectors can be returned from a function. Arrays cannot be copied or assigned directly whereas Vectors can be copied or assigned directly.

Is std :: array slower than C array?

It will provide a value like semantics equally to the other C++ containers. A std::array should have same runtime performance as a c-style array.


2 Answers

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.

like image 81
Ami Tavory Avatar answered Oct 11 '22 04:10

Ami Tavory


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.

like image 44
Ari Hietanen Avatar answered Oct 11 '22 03:10

Ari Hietanen