You can access the elements of pairs inside vector in C++17
in a following style by combining range-based for
loop and structured bindings. Example:
for (auto& [x, y] : pts) {
cin >> x >> y;
}
where pts
is a vector of pairs. &
is used to make formal "uniquely-named variable" e
of structured binding a reference so that x
and y
referring to subobjects of e
refer to original pair inside pts
, which can be modified this way (e.g. cin
can be used to input to it). Without &
, e
would be a copy (to subobjects of which x
and y
again refer). Example using your VectorOfPairs
:
for (auto [pFirst, pSecond] : VectorOfPairs ) {
// ...
}
Also you can make e
a reference to const when modification through structured binding is not needed and you want to avoid potentially expensive copy of a pair (though this should not be a problem in your case since pair object consisting of 2 pointers is pretty small and cheap to copy). Example:
for (const auto& [pFirst, pSecond] : VectorOfPairs ) {
// ...
}
auto
. No downvote tho, good answer. – Clamp