Element at index in a std::set?

前端 未结 6 447
太阳男子
太阳男子 2020-12-03 00:46

I\'ve stumbled upon this problem: I can\'t seem to select the item at the index\' position in a normal std::set. Is this a bug in STD?

Below a simple ex

6条回答
  •  渐次进展
    2020-12-03 01:50

    It doesn't cause a crash, it just doesn't compile. set doesn't have access by index.

    You can get the nth element like this:

    std::set::iterator it = my_set.begin();
    std::advance(it, n);
    int x = *it;
    

    Assuming my_set.size() > n, of course. You should be aware that this operation takes time approximately proportional to n. In C++11 there's a nicer way of writing it:

    int x = *std::next(my_set.begin(), n);
    

    Again, you have to know that n is in bounds first.

提交回复
热议问题