【发布时间】:2025-12-06 04:25:01
【问题描述】:
我有以下带有 C++ STL 向量的 C++ 代码,
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector <int> v;
for (int i=0; i<15; i++)
v.push_back (i);
cout << v[10] << endl;
return 0;
}
它通常打印存储在第 10 个索引中的元素。输出为 10。
但我也尝试了同样的 C++ STL 设置,
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set <int> myset;
for (int i=0; i<15; i++)
myset.insert (i);
cout << myset[10] << endl;
return 0;
}
它给了我编译错误,显示以下消息:(
prog.cpp:在函数“int main()”中:
prog.cpp:12:18: error: no match for ‘operator[]’(操作数类型是 ‘std::set’ 和 ‘int’) cout
所以,我的问题是,有什么方法可以打印 STL 集合的任何元素,就像 C++ 中的 STL 向量一样?如果是,怎么做?
同时,我们可以使用迭代器,但据我所知,它可以与完整的集合一起使用。 :)
【问题讨论】:
-
迭代器应该可以解决问题。
-
因为 set 没有索引访问权限。
-
您的示例是一个玩具,但您应该记住
std::set不存储重复项。如果您每次都将循环重写为insert(1)会怎样——您怎么知道10在范围内?即使使用迭代器,您也会越界访问项目,因为该集合仅包含 1 个项目。 -
我的意思是,如果您依赖
[ ]访问std::set中的项目,那么您的程序存在设计缺陷。 -
顺便问一下,你确定你真的想要集合的“第 10 个元素”吗?我的意思是,集合中的顺序对你来说重要吗?