Получить элемент из произвольного индекса в наборе - PullRequest
10 голосов
/ 18 января 2012

У меня есть набор типа set<int>, и я хочу получить итератор в другое место, а не в начало.

Я делаю следующее:

set<int>::iterator it = myset.begin() + 5;

Мне любопытно, почему это не работает и как правильно доставить итератор туда, куда я хочу.

Ответы [ 2 ]

20 голосов
/ 18 января 2012

myset.begin() + 5; работает только для итераторов с произвольным доступом, которые не являются итераторами из std::set.

Для входных итераторов есть функция std::advance:

set<int>::iterator it = myset.begin();
std::advance(it, 5); // now it is advanced by five

В C ++ 11 есть также std::next, который похож, но не меняет своего аргумента:

auto it = std::next(myset.begin(), 5);

std::next требуется прямой итератор. Но поскольку std::set<int>::iterator является двунаправленным итератором, то и advance, и next будут работать.

0 голосов
/ 27 мая 2018

Получить элемент по индексу из C ++ 11 std :: set

std::set в C ++ не имеет метода получения по индексу, поэтому вам придется свернуть свой собственный, выполнив итерациюперечислите себя и скопируйте в массив, затем индексируйте его.

Например:

#include<iostream> 
#include<set> 
using namespace std; 
int main(){ 

    set<int> uniqueItems;        //instantiate a new empty set of integers 
    uniqueItems.insert(10); 
    uniqueItems.insert(20);      //insert three values into the set 
    uniqueItems.insert(30); 

    int myarray[uniqueItems.size()];    //create an int array of same size as the  
                                        //set<int> to accomodate elements 

    int i = 0;  
    for (const int &num : uniqueItems){ //iterate over the set 
        myarray[i] = num;               //assign it to the appropriate array 
        i++;                            //element and increment 
    }   

    cout << myarray[0] << endl;   //get index at zero, prints 10 
    cout << myarray[1] << endl;   //get index at one, prints 20 
    cout << myarray[2] << endl;   //get index at two, prints 30 

} 

Или удобная функция денди, чтобы пройти через нее и вернуть правильную:

int getSetAtIndex(set<int> myset, int index){ 
    int i = 0;  
    for (const int &num : myset){     //iterate over the set 
        if (i++ == index){                       
            return num;
        }
    }
    string msg = "index " + to_string(index) + \ 
        "is out of range"; 
    cout << msg; 
    exit(8);
} 
int main(){ 
    set<int> uniqueItems;        //instantiate a new empty set of integers 

    uniqueItems.insert(10); 
    uniqueItems.insert(20);      //insert three values into the set
    uniqueItems.insert(30); 

    cout << getSetAtIndex(uniqueItems, 1); 
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...