首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新手请问关于C++中find的有关问题

2012-09-10 
新手请教关于C++中find的问题代码如下:#include iostream#include list#include string#include al

新手请教关于C++中find的问题
代码如下:

#include <iostream>
#include <list>
#include <string>
#include <algorithm> //这里是用于查找的函数头文件

using namespace std;

typedef struct Node {
char name[1024];
char src[1024];
}node;

typedef list<node>like;


int main(void)

{
like link;
like::iterator j;
like::iterator k;
int i = 0;
char name[1024];
char src[1024];
node a;
for (i = 0; i < 10; i++)
{
printf("please input name:");
scanf("%s", name);
printf("please input src:");
scanf("%s", src);
strncpy(a.name, name, sizeof(name));
strncpy(a.src, src, sizeof(src));
link.push_back(a);

k = find (link.begin(), link.end(), a.name);//问题出在这里

if (k != link.end())
{
strncpy(a.src , src, sizeof(src));
}
else
{
link.push_back(a);
}
}

for (j = link.begin(); j != link.end(); j++)
{
cout << j->name ;
cout << j->src ;
}
return 0;
}
错误提示:
list.cpp
d:\vc6\vc98\include\algorithm(43) : error C2676: binary '==' : 'struct Node' does not define this operator or a conversion to a type acceptable to the predefined operator
  F:\编程例子\list.cpp(36) : see reference to function template instantiation 'class std::list<struct Node,class std::allocator<struct Node> >::iterator __cdecl std::find(class std::list<struct Node,class std::allocator<struct Node> >::iterato
r,class std::list<struct Node,class std::allocator<struct Node> >::iterator,const char (&)[1024])' being compiled
执行 cl.exe 时出错.

我百度来的用法,可是为什么一直在报错。请高手指点,谢谢!

[解决办法]
Node 没有重载运算符。
[解决办法]
在一个list中找指定的item,实际就是一个比较的过程,拿你指定Item与list第一个item开始找与指定item相等的项,因为list中是你自定义数据类型,默认没有相等等操作,所以你需要重载这个运算符,让编译器知道怎么样才认为是相等
[解决办法]
[code=C/C++]
template<class InputIterator, class T>
InputIterator find ( InputIterator first, InputIterator last, const T& value )
{
for ( ;first!=last; first++) if ( *first==value ) break;
return first;
}
你定义一个 ==重载吧!
[code]

热点排行