访问存储在迭代器中的数据
Get access to the data stored in iterator
我试图更适应std::multiset和std::p air。所以我写了一个小的主程序,它创建了一个多集并将元素推入其中,如下所示。
#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::p air 元素的第一个值?
由于运算符优先级,您基本上写*(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 和浮点数。
相关文章:
- 如何复制只有两个迭代器的数据?
- 复杂数据类型向量的迭代器
- 如何将字符串迭代器指向的数据推回字符串向量
- 如何从数据结构的向量中收集迭代器
- 访问存储在迭代器中的数据
- 仅覆盖自定义数据架构的迭代器的操作员*()
- C /STL公共迭代器,用于深嵌套的私人数据
- 结构"node"的迭代器不允许数据检索
- 为什么迭代器指向的数据在从列表中删除后保留
- 给定同一数据结构的两个迭代器,如何检查哪个迭代器在另一个之前
- 如何使用STL迭代器和reverse_iterator处理数据
- STL如何用非线性数据结构实现反向迭代器去引用
- 集合数据结构中的 end() 迭代器应该返回什么
- C++ - 如何在自定义模板化数据容器中的迭代器上使用 advance() 启用 ADL
- 谁应该有一个迭代器,我的数据类或该类中的实际列表
- 友元迭代器是否可以访问非静态数据成员
- C++:从只能通过迭代器访问的数据类型中高效地提取元素子集
- 保持数据迭代器的矢量
- 排序后的数据结构通过迭代器快速迭代、插入、删除
- 如何确保迭代器模板形参与模板类的模板形参具有相同的数据类型