简体   繁体   中英

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? I only ask because std::tuple doesnt feel like a container, since it requires things such as std::get and 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. 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. For example, a std::tuple is useful when a function needs to return multiple objects. A container, on the other hand, contains multiple elements of the same type (perhaps a varying amount).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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