关于STL的vector查找问题

squn 2006-10-24 01:11:31
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct Npos{
int x;
int y;
int f;
};
typedef Npos npos;
void main(){
npos a;
npos b;
b.x=5;
b.y=9;
b.f=3;
a.x=2;
a.y=6;
a.f=2;
std::vector<npos> sai;
sai.push_back(a);
sai.push_back(b);
std::vector<npos>::const_iterator ss;
ss=std::find(sai.begin(),sai.end(),2);
cout<<ss<<endl;
}
里面那个查找有错误
c:\sai\include\algorithm(43) : error C2676: binary '==' : 'struct Npos' does not define this operator or a conversion to a type acceptable to the predefined operator
C:\Documents and Settings\Administrator\abs.cpp(25) : see reference to function template instantiation 'struct Npos *__cdecl std::find(struct Npos *,struct Npos *,const int &)' being compiled
执行 cl.exe 时出错.

哪位高手可以指点一下,还有就是写一下可以实现的代码!万分感谢
...全文
1384 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
squn 2006-10-24
  • 打赏
  • 举报
回复
非常感谢!
celeil 2006-10-24
  • 打赏
  • 举报
回复
你怎么能在vector<npos>里find一个int值呢?
mstlq 2006-10-24
  • 打赏
  • 举报
回复
ss=std::find(sai.begin(),sai.end(),Npos(2,9,2));
改成
ss=std::find(sai.begin(),sai.end(),Npos(2,6,2));
就能把a变量找出来了,呵呵
mstlq 2006-10-24
  • 打赏
  • 举报
回复
没有重载“==”运算符,编译器不懂怎么判断一个npos对象和一个int对象在什么情况下是“相等的”……
下面是一个可用的例子

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct Npos{
int x;
int y;
int f;
bool operator==(const Npos npos)
{
return x==npos.x && y==npos.y && f==npos.f;
}
Npos(){}
Npos(int a,int b,int c)
{
x=a;y=b;f=c;
}
};
typedef Npos npos;
void main(){
npos a;
npos b;
b.x=5;
b.y=9;
b.f=3;
a.x=2;
a.y=6;
a.f=2;
std::vector<npos> sai;
sai.push_back(a);
sai.push_back(b);
std::vector<npos>::const_iterator ss;
ss=std::find(sai.begin(),sai.end(),Npos(2,9,2));
if (ss!=sai.end())
cout<<(*ss).x<<endl<< (*ss).y<<endl <<(*ss).f <<endl;
else
cout<<"can not find!"<<endl;
}


楼主也可以在npos中自定义一个
bool operator==(const int i)

这样的话,调用ss=std::find(sai.begin(),sai.end(),2);之类的语句就不会出错了。
mjken 2006-10-24
  • 打赏
  • 举报
回复
哈哈 找到了答案就要给人家分数喔 squn你这个小子

64,439

社区成员

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

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