简体   繁体   中英

C++ tuples: time complexity for get(i)

I want to access element at position i of a tuple( https://en.cppreference.com/w/cpp/utility/tuple/get ) in c++.\ If for instance I have:\

std::tuple <int, int, int> t{1, 2, 3};
int x = std::get<2>(t);

Is it constant time to access an element or linear?

The two following blocks of code are functionally equivalent:

std::tuple<int, int, int> t{1, 2, 3};
int x = std::get<2>(t);
struct __type_for_tuple_iii {int __1; int __2; int __3;};
__type_for_tuple_iii t{1, 2, 3};
int x = t._2;

NB This remains true no matter how many members the tuple has.

As you can see, std::get<>(std::tuple) doesn't really do much actual "work" per-se. More specifically, almost all of the work it does is guaranteed to be feasible during compilation. All that's left at runtime is a simple memory offset.

So you might as well be asking: "What is the complexity of accessing a struct's member?".

That answer to which is: O(1) , no matter how big the struct is, so the same goes for tuples and std::get<> .

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