如何更新 std::vector<pair<int, int>> 中最近输入的元素?

How to update recently entered element in std::vector<pair<int, int>>?

如何更新成对类型的任何向量 class 中成对的值?

示例:

V.push_back(make_pair(1, 3));

如果我希望将 3 更新为 5 或其他内容,我该如何实现?

如果 i 是包含您要更新的 std::pairstd::vector 中的索引:

vec.at(i).second = 5;

另请注意,std::pair 覆盖了 = 运算符,因此您可以再次分配整个对:

vec.at(i) = std::make_pair(val1, val2);

您在 vector 中访问一个值,只需设置您想要更改的值。假设您对 vector.

具有可变访问权限
V.back().first = 1;
V.back().second = 2;

如果您知道项目在 vector 中的索引,您可以使用 operator[]at 来获取项目的引用。您也可以将新值复制到相同位置。

V[0] = std::make_pair(3, 5);

假设您想要在插入 std::vector<std::pair<int, int>>.

之后更新 last std::pair 输入

you can make use of second overload of std::vector::emplace_back中,returns对插入元素的引用

#include <vector>

std::vector<std::pair<int, int>> vec;
auto &pair = vec.emplace_back(1, 3); // construct in-place and get the reference to the inserted element
pair.second = 5;                     // change the value directly like this

更新:

, the same can be achieved by the std::vector::insert成员中,其中returns迭代器指向插入的元素。

#include <vector>

std::vector<std::pair<int, int>> vec;
// insert the element to vec and get the iterator pointing to the element
const auto iter = vec.insert(vec.cend(), { 1, 3 });
iter->second = 5; // change the value

如果要修改向量 V 中的所有对,请使用 for 循环进行迭代:

 for (int i = 0; i < V.size(); i++)
 {  
     V[i].first = // some value;
     V[i].second = // some value;
 }