【发布时间】:2016-05-29 03:16:47
【问题描述】:
我正在尝试搜索对象指针向量。我的代码将提示用户输入名字或姓氏并打印出 Profile 对象信息。
即用户将读取如下文本文件。
Homer Simpson hs742 donut123!
Bart Simpson bs1 don't-have-a-cow-man
Smith Wesson sw666 gunsgunsguns
然后当用户输入像 Homer 这样的名字或姓氏时,代码将搜索向量并打印出来:
Homer Simpson hs742 donut123!
我的问题是尝试搜索和遍历我的vector<Profile *>。我尝试搜索互联网并找到find_if,但它不起作用。
int main(){
string fn;
string ln;
string usn;
string pswrd;
string name;
vector <Profile *> pvector; //vector of object pointers
ifstream myfile("file1.txt");
if(myfile.is_open())
{
while (myfile >> fn >>ln >>usn>>pswrd)
{
Profile * prf;
prf = new Profile(fn, ln, usn, pswrd);
pvector.push_back(prf);
}
} else cout <<"Error opening file" <<endl;
myfile.close();
do {
cout<<"Enter name to search for: ";
cin>>name;
//search vector
vector<Profile *>::iterator it = find_if(pvector.begin(), pvector.end(), name);
cout << "name: " << *it << '\n';
} while (name != "end");
return 0;
}
【问题讨论】:
-
您希望有一个 lambda 函数将名称与
Profile::name进行比较。 -
虽然 Galik 的回答是正确的,但对于这项任务,您可能需要地图而不是矢量。
-
你需要一个指针向量吗?最好有一个对象向量。目前你的代码泄露了。
-
一旦你得到它的工作,它可能值得审查:codereview.stackexchange.com
标签: c++ vector predicate stl-algorithm