I'm trying to get more comfortable with std::multiset and std::pair. So I wrote a little main program which creates a multiset and pushes elements into it, as you can see below.
#include <set>
#include <utility>
#include <iostream>
#include <string>
int main()
{
std::cout << "Hello World" << std::endl;
/*
std::multiset<std::pair<int, float> > set;
std::multiset<std::pair<int, float> >::iterator it;
set.insert(std::make_pair(534, 5.3));
set.insert(std::make_pair(22, 9.2));*/
std::multiset<int> set;
std::multiset<int>::iterator it;
set.insert(43);
set.insert(45);
set.insert(32);
for(it = set.begin(); it != set.end(); it++)
{
std::cout << *it << std::endl;
}
std::cout << "Bye" << std::endl;
return 1;
}
When I create an int-multiset everything works fine. But when I comment the second multiset-block out and use the first one instead. I get following compile error:
std::cout << *it << std::endl;no match for 'operator<<' (operand types are'std::ostream {aka std::basic_ostream<char>}' and 'const std::pai<int, float>')
So I replaced
std::cout << *it << std::endl;
with
std::cout << *it.first << std::endl;
and get following error:
‘std::multiset<std::pair<int, float> >::iterator {aka struct std::_Rb_tree_const_iterator<std::pair<int, float> >}’ has no member named ‘first’
How can I fix this, to get access to the first value of the std::pair element stored inside the multiset?
Due to operator precedence, you essentially wrote *(it.first)
. You can use parenthesis to specify the order you want the operators to resolve :
std::cout << (*it).first << std::endl;
Though you can just use operator->
instead :
std::cout << it->first << std::endl;