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;
}
Share:
12,574

Related videos on Youtube

Bobtheblobber
Author by

Bobtheblobber

Updated on June 04, 2022

Comments

  • Bobtheblobber
    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
      CinCout over 5 years
      You are overwriting pairVec. Hint: It is a single pair, not a vector of pairs.
    • n. m.
      n. m. over 5 years
      How many elements do you expect to see printed?
    • molbdnilo
      molbdnilo over 5 years
      What would the type of iter be? Try to fill in the type yourself, without writing auto.
    • YSC
      YSC over 5 years
      What is the expected behavior of your code?
  • Bobtheblobber
    Bobtheblobber over 5 years
    Thanks for your time! Did I mention about the vector? I just need to iterate over the pair and print the elements
  • n. m.
    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 variable pairVec?
  • Bobtheblobber
    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
    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` to iter->first and likewise for iter.second.
  • von spotz
    von spotz over 3 years
    The 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