C++ 如何按索引设置 std::tuple 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7453600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:57:43  来源:igfitidea点击:

How to set std::tuple element by index?

c++templatesindexingtuples

提问by Behrouz.M

One can get an element from std::tupleby index using std::get. Analogically, how to settuple's element by index?

可以std::tuple使用std::get. 类似地,如何通过索引设置元组的元素?

回答by Nicol Bolas

std::getreturns a reference to the value. So you set the value like this:

std::get返回对值的引用。所以你设置这样的值:

std::get<0>(myTuple) = newValue;

This of course assumes that myTupleis non-const. You can even move items out of a tuple via std::move, by invoking it on the tuple:

这当然假设它myTuple是非常量的。您甚至可以通过std::move在元组上调用它来将项目移出元组:

auto movedTo = std::get<0>(std::move(myTuple));

回答by amit

The non-const version of getreturns a reference. You can assign to the reference. For example, suppose tis tuple, then: get<0>(t) = 3;

的非常量版本get返回一个引用。您可以分配给参考。例如,假设t是元组,则:get<0>(t) = 3;