How can I loop over pair in c++
12,574
You're not making a vector at all. You probably wanted to do this instead:
int main()
{
std::vector<pair<int, string>> pairVec; // create a vector of pairs
pairVec.emplace_back(1, "One"); // adding pairs to the vector
pairVec.emplace_back(2, "Two");
pairVec.emplace_back(3, "Three");
for (auto iter : pairVec) {
std::cout << "First: " << iter.first << ", Second: "
<< iter.second << std::endl;
}
return 0;
}
Related videos on Youtube
Author by
Bobtheblobber
Updated on June 04, 2022Comments
-
Bobtheblobber almost 2 years
I am trying to print the elements in pair, but it's throwing an error: "no matching function call"
Code:#include <utility> #include <iostream> using namespace std; int main() { pair<int, string> pairVec; pairVec = make_pair(1, "One"); pairVec = make_pair(2, "Two"); pairVec = make_pair(3, "Three"); for(auto iter:pairVec) { std::cout << "First: " << iter.first << ", Second: " << iter.second << std::endl; } return 0; }
-
CinCout over 5 yearsYou are overwriting
pairVec
. Hint: It is a single pair, not avector
ofpair
s. -
n. m. over 5 yearsHow many elements do you expect to see printed?
-
molbdnilo over 5 yearsWhat would the type of
iter
be? Try to fill in the type yourself, without writingauto
. -
YSC over 5 yearsWhat is the expected behavior of your code?
-
-
Bobtheblobber over 5 yearsThanks for your time! Did I mention about the vector? I just need to iterate over the pair and print the elements
-
n. m. over 5 years@DheerajN Did I mention about the vector? Yes you very much did. Why did you
#include <vector>
? Why did you call your variablepairVec
? -
Bobtheblobber over 5 years@Blaze It is working fine! But when I mention the type of iterator instead of auto: std::vector<pair<int, string>>::const_iterator it, with regular for loop using it.begin....., it is throwing error "has no member named ‘first’"
-
Blaze over 5 years@DheerajN that's because the definition in that regular loop is different than what was
auto
-defined with the range based for loop (which is something rather unwieldy, in MSVC at least). But that works if you change ` iter.first` toiter->first
and likewise foriter.second
. -
von spotz over 3 yearsThe purpose of the
std::pair
here is to put order into the elements on the right hand side (std::pair.second
). How would you change order, like swapping elements std::vector<std::pair<3, ...>> with std::vector<std::pair<8, ...>> ? Cheers