2

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;
}
seth
  • 25
  • 4
  • With range-v3: `for (auto e : s | ranges::views::stride(2)) {std::cout << e << std::endl; }` – Jarod42 May 13 '20 at 09:12
  • 1
    `std::advance(it, 2);` as `std::set::iterator` are not random access iterator. – Jarod42 May 13 '20 at 09:15
  • 1
    Not directly related, but see those questions as well: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Yksisarvinen May 13 '20 at 09:18

1 Answers1

3

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))
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • I would not use `std::prev` as the condition is never met for containers with an even number of elements. Also `std::advance` changes the iterator in place and doesn't return anything. https://gcc.godbolt.org/z/cTHaua – Simon Kraemer May 13 '20 at 09:43
  • 3
    Re: "It depends on the container type" -- that's correct as far as it goes, but the true rule is that it depends on the **iterator** type. A pair of iterators designates a sequence of values. Containers are one way of managing sequences, but they are not the only way. For example, `std::istream_iterator` extracts elements from an `std::istream` object, which is not (except by an extremely forced definition) a container. +1. – Pete Becker May 13 '20 at 12:09