Search code examples
c++c++11stlstdmapstdset

How to access map of set of pairs elements?


#include <iostream>
#include <map>
#include <set>
#include <utility>
int main()
{
    std::map<int,std::set<std::pair<int,int>>>map1;

    for(int i = 0; i != 3; ++i) 
        map1[i].insert({i+1,i+2});

    for(auto i : map1){

        std::cout<<i.first<<" ";

        pair<int,int> j = i.second;

        j.first<<" "<<j.second<<"\n";

    }
    return 0;
}          

error: conversion from std::set < std::pair< int, int > > to non-scalar type std::pair < int, int > requested pair< int, int > j = i.second;


Solution

  • i.second is the std::set, and not the internal std::pair.

    You should do something like this:

    for(auto i : map1)
    {
        std::cout<< i.first << " ";
        std::set<std::pair<int,int>> j = i.second;
        for (const auto& k : j)
        {
            std::cout << k.first<<" "<<k.second<<"\n";
        }
    }
    

    Demo