auto str=lower_bound(s.begin(),s.end(),n);
cout<<std::distance(s.begin()+1,str)+1;
Why +1
not working after s.begin()
? It shows that there is no match for operator+
(operand types are 'std::set::iterator'...)
std::set
iterators are bi-directional iterators, which are required only to implement the --
and ++
operators. Random-access iterators implement +
/ -
and +=
/ -=
operators.
You can use std::advance()
or std::next()
to move an iterator forward when it doesn't implement operator+
, eg:
auto str = std::lower_bound(s.begin(), s.end(), n);
auto iter = s.begin();
std::advance(iter, 1);
cout << std::distance(iter, str) + 1;
auto str = std::lower_bound(s.begin(), s.end(), n);
cout << std::distance(std::next(s.begin()), str) + 1;
A std::set::iterator
does not support operator+
(it's a LegacyBidirectionalIterator supporting operator--
and operator++
), so it fails here:
s.begin() + 1
Skip +1
and it'll work, but it'll not be a single operation. I'll have to step forward from s.begin()
to str
in order to calculate the distance:
std::cout << std::distance(s.begin(), str);
Note: In order to get the same result as std::distance(s.begin() + 1, str) + 1;
would have given if it had worked, you must skip the +1
you have after std::distance()
too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.