简体   繁体   English

C++ 设置迭代器错误:集合中的“operator+=”不匹配

[英]C++ set iterator error: no match for ‘operator+=’ in set

auto str=lower_bound(s.begin(),s.end(),n);


cout<<std::distance(s.begin()+1,str)+1;

Why +1 not working after s.begin() ?为什么+1s.begin()之后不起作用? It shows that there is no match for operator+ (operand types are 'std::set::iterator'...)它表明operator+不匹配(操作数类型为 'std::set::iterator'...)

std::set iterators are bi-directional iterators, which are required only to implement the -- and ++ operators. std::set迭代器是双向迭代器,只需要实现--++运算符。 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:当迭代器没有实现operator+时,您可以使用std::advance()std::next()向前移动迭代器,例如:

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:一个std::set::iterator不支持operator+ (它是一个LegacyBidirectionalIterator支持operator--operator++ ),所以它在这里失败:

s.begin() + 1

Skip +1 and it'll work, but it'll not be a single operation.跳过+1 ,它会起作用,但它不会是一个单一的操作。 I'll have to step forward from s.begin() to str in order to calculate the distance:我必须从s.begin()前进到str才能计算距离:

std::cout << std::distance(s.begin(), str);

Note: In order to get the same result as std::distance(s.begin() + 1, str) + 1;注意:为了得到与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.如果它起作用了就会给出,你也必须跳过std::distance()之后的+1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM