gpt4 book ai didi

c++ - 是否有可能在 C++ STL 中获取集合的单个元素?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:57 24 4
gpt4 key购买 nike

我有以下带有 C++ STL vector 的 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: In function ‘int main()’:

prog.cpp:12:18: error: no match for ‘operator[]’ (operand types are ‘std::set’ and ‘int’) cout << myset[10] << endl;

所以,我的问题是,是否有任何方法可以像 C++ 中的 STL vector 一样打印 STL 集的任何元素?如果是,怎么办?

同时,我们可以使用迭代器,但据我所知,它可以使用完整的集合。 :)

最佳答案

是的,这是可能的,但不能使用 operator[]

std::set 不提供 operator[],因为它不是随机访问容器。相反,必须使用迭代器来访问它的元素。

auto first = myset.begin(); // get iterator to 1st element
std::advance(first, 9); // advance by 9
std::cout << *first; // 10th element

请注意,std::set 是一个有序容器,元素不会按照您插入它们的顺序出现。

关于c++ - 是否有可能在 C++ STL 中获取集合的单个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44288724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com