1

How can I access ith element of an ordered set using iterator. This is what I have tried

vector<int> array(N);
set<int> myset;
for(i=0;i<N;i++)
{
    cin>>array[i];
    myset.insert(array[i]);
}
set<int> ::iterator it=myset.begin();
i = 2;
cout<<*(it+i);

Which gives me an error

Compilation Error:
prog.cpp: In function ‘int main()’:
prog.cpp:19:16: error: no match for ‘operator+’ (operand types are ‘std::set<int>::iterator {aka std::_Rb_tree_const_iterator<int>}’ and ‘int’)
      cout<<*(it+i);
                ^
In file included from /usr/include/c++/5/bits/stl_algobase.h:67:0,
                 from /usr/include/c++/5/bits/char_traits.h:39,
                 from /usr/include/c++/5/ios:40,
                 from /usr/include/c++/5/istream:38,
                 from /usr/include/c++/5/sstream:38,
                 from /usr/include/c++/5/complex:45,
                 from /usr/include/c++/5/ccomplex:38,
                 from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:52,
                 from prog.cpp:1:
/usr/include/c++/5/bits/stl_iterator.h:341:5: note: candidate: template<class _Iterator> std::reverse_iterator<_Iterator> std::operator+(typename std::reverse_iterator<_Iterator>::difference_type, const std::reverse_iterator<_Iterator>&)
     operator+(typename .................

My question is when it++ works and increment the pointer to point to next block. Then why not adding integer to iterator here? How can I achieve this?

Himanshu Poddar
  • 3,438
  • 5
  • 34
  • 67
  • @idmean not fully, can you tell me since iterator is a pointer why can't we access the element like `*(it+5)` – Himanshu Poddar Nov 15 '19 at 10:08
  • 1
    An iterator is not a pointer. An iterator is an object that you can dereference and increment. There are no other guarantees about this object (such as adding arbitrary values.) – idmean Nov 15 '19 at 10:09
  • What my whole life was a lie. I used to think that since we are dereferencing using `*` it must be a pointer. How can objects be dereferenced like this. What type of object is it? – Himanshu Poddar Nov 15 '19 at 10:10
  • This is totally up to the implementation. You can overload `*` as you wish in C++. Please learn more about the iterator trait here: https://en.cppreference.com/w/cpp/named_req/Iterator – idmean Nov 15 '19 at 10:12

0 Answers0