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



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

例:

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

如果我想更新35或其他东西,我该如何实现?

您可以在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>>后更新最后std::pair输入。

c++17 中,你可以使用 std::vector::emplace_back 的第二个重载,它返回对插入元素的引用

#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
<小时 />

更新:

c++11 中,std::vector::insert 成员也可以实现相同的目的,该成员返回指向插入元素的迭代器

#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

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

vec.at(i).second = 5;

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

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

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

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

最新更新