一个关于迭代器和指针的问题

asd_787746056 2012-09-12 09:29:31
#include<iostream>
#include<vector>

using namespace std;

vector<int>::iterator findInt( vector<int>::iterator beg, vector<int>::iterator end, int ival)
{
while( beg != end)
{
if( *beg == ival )
break;
else
++beg;
}
return beg;

}

int main()
{
int p[] = { 1,2,3,4,5};
cout << "请输入要查找的正整数: " << endl;
int ival ;
cin >> ival ;

vector<int>::iterator it = findInt(p,p+5, ival);

if( it != (p+5))
cout << " find" << endl ;
else
cout << "not fine" << endl ;
system("pause");
return 0;
}


运行时错误是:
1.error C2664: “findInt”: 不能将参数 1 从“int [5]”转换为“std::_Vector_iterator<_Ty,_Alloc>”
2. error C2678: 二进制“!=”: 没有找到接受“std::_Vector_iterator<_Ty,_Alloc>”类型的左操作数的运算符(或没有可接受的转换)

问题:不能将指针传给迭代器吗?
以上程序中,findInt函数需要两个迭代器参数,实际传递的是指针,就会出错,为什么呢?
...全文
131 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
rydiy 2012-09-12
  • 打赏
  • 举报
回复
1、vector的迭代器也是一种数据类型,且是根据不同的vector定义而不同,所以int[] 转 vector<int>::iterator 显然是不行的。
2、迭代器只能跟另一个迭代器来做== 或 != 比较

再说, 你代码里没用到vector干嘛要用vector的迭代器呢? 直接改 int* 不就ok了吗?
zhaoZero41 2012-09-12
  • 打赏
  • 举报
回复
迭代器从某种角度上来说,就是指针,因为迭代器和指针具有类似的功能。
但是,上面程序中p并不是vector<int>类型的迭代器,而是int *类型的指针。这两种类型之间并不能隐式转换,你这么用当然是会出错的。就好比你拿一个int *指针直接去指向一个string对象的地址,会报错么?

数组指针适用于容器类型的初始化,直接想去当做迭代器肯定是不行的。
pengzhixi 2012-09-12
  • 打赏
  • 举报
回复
两种不同的类型当然会有问题。
ri_aje 2012-09-12
  • 打赏
  • 举报
回复
把接口改成这样再试一下.

template <typename IT>
IT findInt( IT beg, IT end, int ival);

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧