是否可以在C++ STL中获取集合中的单个元素?

Sha*_*hir 1 c++ stl vector set c++11

我有以下带有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;
}
Run Code Online (Sandbox Code Playgroud)

它通常会打印存储在第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;
}
Run Code Online (Sandbox Code Playgroud)

它给我编译错误显示以下消息:(

prog.cpp:在函数'int main()'中:

prog.cpp:12:18:错误:'operator []'不匹配(操作数类型是'std :: set'和'int')cout << myset [10] << endl;

所以,我的问题是,有没有办法在C++中打印STL向量的任何元素?如果有,怎么样?

同时我们可以使用迭代器,但据我所知它可以使用全套.:)

Dei*_*Dei 7

是的,这是可能的,但没有使用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
Run Code Online (Sandbox Code Playgroud)

请注意,这std::set是一个有序容器,元素不会按插入顺序显示.


Sha*_*mar 5

您无法通过索引访问集合元素。但是您可以std::advance在迭代器上使用。

set<int>::iterator it = myset.begin();
std::advance(it, 5); // advanced by five
Run Code Online (Sandbox Code Playgroud)

std::next也存在于C++11,

auto it = std::next(myset.begin(), 5);
Run Code Online (Sandbox Code Playgroud)

这两个版本之间的差异解释如下: What's the Difference Between std::advance and std::next?