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
How to set std::tuple element by index?
提问by Behrouz.M
One can get an element from std::tuple
by index using std::get
.
Analogically, how to settuple's element by index?
可以std::tuple
使用std::get
. 类似地,如何通过索引设置元组的元素?
回答by Nicol Bolas
std::get
returns a reference to the value. So you set the value like this:
std::get
返回对值的引用。所以你设置这样的值:
std::get<0>(myTuple) = newValue;
This of course assumes that myTuple
is 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 get
returns a reference. You can assign to the reference. For example, suppose t
is tuple, then: get<0>(t) = 3;
的非常量版本get
返回一个引用。您可以分配给参考。例如,假设t
是元组,则:get<0>(t) = 3;