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.
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.
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.
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.
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.
For this specific case, I'd have to disagree with the comments. For homogeneous type containers - as is the case here (all int
s) - 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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With