在矢量中搜索项目
Search item in a vector
我想在我的结构中找到一个元素(姓氏)
struct student
{
char name[20];
char surname[20];
int marks;
};
Ofc从键盘定义矢量和搜索元素
vector <student> v;
char search_surname[20];
我是按功能输入元素:
int size = v.size();
v.push_back(student());
cout << "Input name: " << endl;
cin >> v[size].name;
cout << "Input surname: " << endl;
cin >> v[size].surname;
cout << "Input marks: " << endl;
cin >> v[size].marks;
现在,例如,当我的结构中有三个姓氏(牛顿、爱因斯坦、帕斯卡尔)时,我想找到姓牛顿,并用牛顿(名称、姓氏、标记)计算结构的所有细节。我不知道该怎么办。
一种暴力方法:
for(vector <student>::iterator it = v.begin(); it != v.end(); it++)
{
if (strcmp(it->surname, "newton") == 0)
{
cout << "name = " << it->name << endl;
cout << "surname = " << it->surname << endl;
cout << "marks = " << it->marks << endl;
}
}
请将#include <cstring>
添加到代码中,以便使用strcmp()
。
使用STL,可以使用<algorithm>
:中的std::find_if
std::vector<student> v;
auto it = std::find_if(v.begin(), v.end(), [](const student& s)
{
return strcmp(s.surname, "newton") == 0;
});
if (it != v.end()) {
std::cout << "name = " << it->name << std::endl;
std::cout << "surname = " << it->surname << std::endl;
std::cout << "marks = " << it->marks << std::endl;
}
注意:我建议使用std::string
而不是char[20]
,因此条件将变为return s.surname == "newton"
。
我最近使用了库<算法>
此函数返回一个迭代器,并在返回值不是end()时指示find。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- 如何从 std::vector 搜索和返回项目
- 在给定的项目列表上实现搜索?
- 根据条件和优先级搜索容器中的项目
- 我想使用列表中的项目在地图中搜索
- STD :: MAP-如何查找或添加,然后可以在一次搜索中删除项目
- 二进制搜索树电影数据库项目
- 搜索匹配两个容器中的项目C++
- 在C++中搜索并删除矢量中的特定项目
- XCode3 - 库搜索路径和项目框架之间的关系
- 搜索函数返回相同的,而不考虑二叉搜索树中存在的项目
- 在矢量中搜索项目
- 在QStringList中搜索特定项目,然后搜索可能包含项目的其他项目
- 在c++中使用STL搜索变量/项目/属性
- 基于排序和搜索算法的c++项目
- 在sqlite3数据库中搜索查询某些项目
- (C++Boost)在列表中查找成员与搜索词匹配的项目
- 使用不在根项目目录上的源文件(包括在搜索路径中的文件)时发生链接错误(Visual C++)