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

最后都变了- 提交于 2020-01-03 17:34:29

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/35743470/stdtuple-vs-stdarray-as-items-of-a-stdvector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!