修改元组c ++向量中的元组

jja*_*son 7 c++ tuples vector c++11

我有一个元组的向量,vector<tuple<int,int>> vector;我想修改它包含的元组之一.

for (std::tuple<int, int> tup : std::vector)
{
    if (get<0>(tup) == k)
    {
        /* change get<1>(tup) to a new value
         * and have that change shown in the vector
         */
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定如何更改元组的值并将更改反映在向量中.我试过用

get<1>(tup) = v;
Run Code Online (Sandbox Code Playgroud)

但这不会改变向量中元组的值.我怎样才能做到这一点?谢谢.

Tar*_*ama 16

tuple通过引用捕获:

for (tuple<int, int> &tup : vector){
//                   ^here
    if (get<0>(tup) == k){
        get<1>(tup) = v;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用`auto`:`for(auto&tup:vector){...}` (4认同)

Joh*_*nck 5

您只需要在for循环中使用引用而不是值:

for (tuple<int, int>& tup : vector){
Run Code Online (Sandbox Code Playgroud)