Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we can't add an iterator with integer?

Tags:

c++

stl

I want to print all the values of a set by iterator. After printing all values I want to print a endl without the last one.Here is my code:

for (set<string> :: iterator it = str_set.begin();it!=str_set.end(); it++)
{
     cout<<*it;
     if((it+1)!=str_set.end())  //here I got error ...
     cout<<endl;
}

But I got an Error while checking if((it+1)!=str_set.end()) .What is the wrong here?

Here is the error message:

error: no match for ‘operator+’ (operand types are ‘std::set<std::__cxx11::basic_string<char> >::iterator’ {aka std::_Rb_tree_const_iterator<std::__cxx11::basic_string<char> >’} and ‘int’)
   92 |         if(it+1!=str_set.end())
      |            ~~^~
      |            |  |
      |            |  int
      |            std::set<std::__cxx11::basic_string<char> >::iterator {aka std::_Rb_tree_const_iterator<std::__cxx11::basic_string<char> >}
like image 314
Imtiaz Mehedi Avatar asked Dec 23 '22 19:12

Imtiaz Mehedi


1 Answers

What is the wrong here?

std::set::iterator is a Constant LegacyBidirectionalIterator. There is no binary + operator between such an object and an int.

You can use std::next to get the next iterator. That would be idiomatic.

 if ( std::next(it) != str_set.end() )
    cout << endl;
like image 151
R Sahu Avatar answered Dec 25 '22 23:12

R Sahu