访问存储在迭代器中的数据

Get access to the data stored in iterator

我正在努力适应 std::multiset 和 std::pair。所以我写了一个小主程序来创建一个多重集并将元素推入其中,如下所示。

#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;
}

当我创建一个 int-multiset 时一切正常。但是当我注释掉第二个多集块并改用第一个时。我收到以下编译错误:

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>')

所以我替换了

std::cout << *it << std::endl;

std::cout << *it.first << std::endl;

并出现以下错误:

‘std::multiset<std::pair<int, float> >::iterator {aka struct std::_Rb_tree_const_iterator<std::pair<int, float> >}’ has no member named ‘first’

我该如何解决这个问题,才能访问存储在多重集中的 std::pair 元素的第一个值?

由于 operator precedence,您基本上写了 *(it.first)。您可以使用括号来指定您希望运算符解析的顺序:

std::cout << (*it).first << std::endl;

尽管您可以只使用 operator-> 来代替 :

std::cout << it->first << std::endl;

迭代器的作用类似于指向基础类型的指针,在本例中为 pair<int, float>

std::cout << it->first << ' ' << it->second << std::endl;

这将输出每对的两个成员,即 int 和 float。