如何在对类型的任何向量类中更新对的值?
示例:
V.push_back(make_pair(1, 3));
如果我想更新3
说5
或其他什么,我该如何实现?
假设你想在插入std::pair
之后更新最后一个std::vector<std::pair<int, int>>
输入。
在c++17中,您可以使用std::vector::emplace_back
的第二个重载,它会向插入的元素返回一个referance:
#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
您可以访问vector
中的值,并设置要更改的值。假设你有可变的访问你的vector
。
V.back().first = 1;
V.back().second = 2;
如果你知道vector
中项目的索引,你可以使用operator[]
或at
来获得对项目的引用。您还可以将新值复制到同一位置。
V[0] = std::make_pair(3, 5);
如果i
是包含std::vector
的std::pair
中的索引,您希望更新:
vec.at(i).second = 5;
另请注意,std::pair
会覆盖=
运算符,因此您可以再次分配整个对:
vec.at(i) = std::make_pair(val1, val2);