返回一个迭代器
我有一个函数,它搜索 STL 容器,然后在找到位置时返回迭代器,但是我收到一些有趣的错误消息,可以告诉我我做错了什么吗?
功能:
std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...
return it;
...
}
错误:
error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &'
I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong?
Function:
std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...
return it;
...
}
Error:
error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的搜索函数返回一个 const_iterator。 您应该返回相同的类型,即
std::vector< CClass >::const_iterator
,或将其转换为std::vector
CClass >::iterator
如果您希望调用者能够通过迭代器修改找到的项目。编辑:看到您的更新后,问题似乎是您的迭代器(它)的类型与函数返回的类型不同。 它们应该是相同的。
Your search function is returning a const_iterator. You should either return the same type, i.e.
std::vector< CClass >::const_iterator
, or cast it to astd::vector< CClass >::iterator
if you intend the caller to be able to modify the found item through the iterator.EDIT: after seeing your update, it seems the problem is your iterator (it) has a different type than your function return. They should be the same.
听起来你的 const_iterators 混淆了。 请发布更多代码,特别是您如何声明迭代器。
Sounds like you have your const_iterators mixed up. Please post more code, specifically how you are declaring your iterator.
您还应该查看 std::find_if() 函数。 这可能是一种更干净的方法。
You should also look at std::find_if() function. It may be a cleaner way to do this.