如何输出vector中的类的成员和binary_search的位置?

vccsdn 2005-04-01 10:04:05
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <functional>
#include <string>
using namespace std;

class A
{
public:
int id;
string name;
};

class comp
{
public:
bool operator() (const A& a, const A& b) const
{
return a.id < b.id;
}
};

int main()
{
vector<A> vt;
A a;
for (int i=0; i<10; i++)
{
a.id = i;
a.name = i;
vt.push_back (a);
}
//下面编译不过去,我要输出vt中包含的所有A类的id
//copy (vt.begin(), vt.end(),
// ostream_iterator<A>(cout, "\n"));

A b;
b.id = 3;
bool ret = binary_search(vt.begin(), vt.end(), b, comp()); //我同时想得到检索到的A的name怎么办?
if (ret)
cout << "Found" << endl;
else
cout << "Not Exist" << endl;
}
...全文
174 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
shine51151 2005-04-01
  • 打赏
  • 举报
回复
binary_search返回bool类型,只能表明元素是否存在,无法返回其它类型值
楼主可以自己设计一个函数,用来返回查找到的下表对应的文件名。
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <functional>
#include <string>
using namespace std;

class A
{
public:
int id;
string name;
};

class comp
{
public:
bool operator() (const A& a, const A& b) const
{
return a.id < b.id;
}
};

int Find(vector<A> vt, int id)
{
int index = -1;
for (int i=0; i<vt.size(); i++)
{
if (vt[i].id==id)
{
index = i;
break;
}
}
if (index >= 0)
return index;
else
return -1;


}

int main()
{
vector<A> vt;
A a;
for (int i=0; i<10; i++)
{
a.id = i;
a.name = "name";//最好单独输入文件名,这样不好控制
vt.push_back (a);
}

//下面编译不过去,我要输出vt中包含的所有A类的id
//copy (vt.begin(), vt.end(),
// ostream_iterator<A>(cout, "\n"));

A b;
b.id = 3;
int index = 0;
index = Find(vt,b.id);
if (index >= 0)
{
cout << "Found" << endl;
cout << vt[index].id << " " << vt[index].name << endl;
}
else
cout << "Not Existed" << endl;
//bool ret = binary_search(vt.begin(), vt.end(), b, comp()); //我同时想得到检索到的A的name怎么办?
/*if (ret)
{
cout << "Found" << endl;
}
else
cout << "Not Existed" << endl;
*/
return 0;
}
zengwujun 2005-04-01
  • 打赏
  • 举报
回复
binary_search返回bool类型,只能表明元素是否存在。
zengwujun 2005-04-01
  • 打赏
  • 举报
回复
这样子可以输出id

class A
{
public:
int id;
string name;
operator int(){return id;}//加上隐式转换
};

copy (vt.begin(), vt.end(),
ostream_iterator<int>(cout, "\n"));//改为int

64,648

社区成员

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

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