如何更新任何对类型向量类中的对值?
例:
V.push_back(make_pair(1, 3));
如果我想更新3
说5
或其他东西,我该如何实现?
您可以在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::pair
的std::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;
}