mercredi 31 mai 2017

Is it possible to get a single element of a set in C++ STL?

I have the following C++ code with C++ STL vector,

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

It normally prints the element that is stored into the 10th index. The output be 10.

But I tried the same thing with C++ STL set also,

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

It gives me Compilation error showing the following messages :(

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;

So, my question is, is there any way to print any element of STL sets alike the STL vectors in C++? if yes, how?

Meanwhile we can use iterators but it can work with the full set, as far I know. :)

Aucun commentaire:

Enregistrer un commentaire