简体   繁体   English

正确使用std :: tuple?

[英]Using std::tuple correctly?

I recently learned how to use std::tuple (I had never needed it before then), and was curious as to when it is the proper time to use it over a container? 我最近学会了如何使用std :: tuple(之前我从未需要它),并且很好奇何时才能在容器上使用它? I only ask because std::tuple doesnt feel like a container, since it requires things such as std::get and std::make_tuple. 我只是问,因为std :: tuple不像容器,因为它需要诸如std :: get和std :: make_tuple之类的东西。

It's more of a replacement for a struct than for a container. 它更像是结构的替代品,而不是容器的替代品。 However, in most cases you are better off actually defining a struct for readability reasons. 但是,在大多数情况下,出于可读性原因,最好实际定义结构。 Tuples are best used in templates with variable number of arguments. 元组最好用于具有可变数量参数的模板中。

std::tuple s contain a fixed number of elements of varying types. std::tuple包含固定数量的不同类型的元素。 You use it when you want to group together a few objects of different types. 当您想要将不同类型的几个对象组合在一起时,可以使用它。 I would use it over a struct when the grouping doesn't have any particularly useful semantics. 当分组没有任何特别有用的语义时,我会在struct使用它。 For example, a std::tuple is useful when a function needs to return multiple objects. 例如,当函数需要返回多个对象时, std::tuple很有用。 A container, on the other hand, contains multiple elements of the same type (perhaps a varying amount). 另一方面,容器包含多个相同类型的元素(可能是不同的数量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM