获取std :: set中第一个/最后一个偏移量的第n个项

时间:2014-02-28 01:44:36

标签: c++ iterator set

因此,如果您想获得std::set<int>中的第一个/最后一个项目,我知道您可以使用:

int j = *(my_set.begin());

但我在循环中有上面的代码,我希望有类似的东西:

while(something){
    int j = *(my_set.begin() + i);
    //
    i++;
}

但是我收到编译错误,说没有运算符“+ =”匹配这些操作数。

1 个答案:

答案 0 :(得分:3)

你可以使用迭代器做一些事情,比如:

for(auto it = begin(your_set); it != end(your_set); ++it){
  //Here you iterator for i'th element in i'th iteration.
  *it; //<--i'th element
 }
//your_set.begin(), your_set.end() in older versions of C++

但也许更好的方法是使用,就像这里:

for(auto& x : your_set) {
  //You have here i'th element of set (by reference) 
  x; //<-- i'th element
 }
//Without & x isn't reference

对于第i个元素,您可以使用std::next

j = *next(begin(my_set), i);

但是...每次使用std :: next对于复杂性来说都是致命的。 Set没有Random Access Iterator,函数std :: next(使用advanceBidirectional Iterator为线性)会线性返回位置。对于n个元素,你有Θ(n 2 复杂度,如果你想使用每个元素一次并且你使用上面提到的方法你有Θ( n)的