How do i iterate over alternate elements(or taking leaps of specific size) in set?

Viewed 118

In other words, what I mean to say is : Is itr+=2 a valid argument in c++ ?, where (itr is an iterator to first element of the set). If so, then the following piece of code should work: In this piece if code, the code written in /comment section/ functions well, while the code not in comment section do not. Help me out to iterate alternate elements.

#include <bits/stdc++.h>
using namespace std;

int main()
{
  set<int> s;
  s.insert(5);
  s.insert(7);
  s.insert(8);
  auto it=s.begin();
  cout<<*it<<'\n';
  it+=2;
  cout<<*it<<'\n';
  /*for(auto it=s.begin();it!=s.end();it++)
    cout<<*it<<" ";*/
  return 0;
}
1 Answers

Is itr+=2 a valid argument in c++?

It depends on the container type. For example, it would be perfectly valid for std::vector or std::array, but not for std::set. Each container, due to its nature, provides different types of iterators. std::set only provides BidirectionalIterator, which do not support jumping over arbitrary number of elements, only incrementation and decrementation.

However, you can use std::advance() from <iterator> library (or just increment the iterator twice). Beware that you must never increment end() iterator, so you need to take it into account in loop condition.

for(auto it=s.begin(); it != s.end() && it != std::prev(s.end()); std::advance(it, 2))
Related