错误C2676:std :: set :: const_iterator没有运算符+功能? [英] Error C2676: std::set::const_iterator doesn't have operator+ function?

查看:92
本文介绍了错误C2676:std :: set :: const_iterator没有运算符+功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::set<int> s = { 1,2,3,4,5 };
std::set<int> s2(s.begin(), s.begin() + 2);

我想将s的多个值关联到s2.但是出现了以下编译错误:

I want to assgin several values of s into s2. But got below compile error:

错误C2676二进制文件'+': 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>' 没有定义此运算符或未将其转换为可接受的类型 预定义

Error C2676 binary '+': 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>' does not define this operator or a conversion to a type acceptable to the predefined

似乎std::set::const_iterator没有operator+方法.

推荐答案

std::set::const_iterator似乎没有operator+方法.

您对此是正确的.

只有 随机访问迭代器 (请参阅链接中的 Expression ). 但是, std::set 仅具有

Operations such as s.begin() + 2 is only possible for random access iterators (see the Expression s in the link). But, std::set has only bidirectional iterator (both std::set::iterator and std::set::const_iterator).

但是,您可以使用 std::next 在一种通用的方式,它返回我们传递的迭代器的第n个后继者.

However, you could use std::next to do this job in a generic way, which returns the nth successor of iterator which we pass.

#include <iterator>  // std::next

std::set<int> s2(s.begin(), std::next(s.begin(), 2));
// or const_iterator    
std::set<int> s3(s.cbegin(), std::next(s.cbegin(), 2));

这篇关于错误C2676:std :: set :: const_iterator没有运算符+功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆