使用矢量搜索名称
searching for name using vectors
本文关键字:搜索 更新时间:2023-10-16
如何搜索用户从程序中输入的名称?目前我有这个供我搜索,但每当程序找到选定的学生时,它就会像一个永无止境的循环一样不停地打印。我也使用多态性,因为学生被分为本地和国际学生。
我曾想过使用stl算法在学生中迭代,但我对stl很陌生。我试过一些来自互联网的例子,但当应用到我的程序时,它总是给我一个错误。
主要功能
int main()
{
clsUniversityProgram objProgram[3];
for (int x = 0; x < 3; x++)
{
objProgram[x].programInfo();
}
vector <clsStudent*> student;
addStudents(student, objProgram);
searchStudent(student);
return 0;
}
void searchStudent(const vector <clsStudent*>& s)
{
string searchName;
const clsStudent *foundStudent;
cout << "nEnter student name to search for. [ENTER] terminates" << endl;
cin >> searchName;
if (s.size() == 0)
cout << "There is 0 student in the database.";
while(searchName.length() != 0)
{
for (int i = 0; i < s.size(); i++)
{
if (s[i]->getName() == searchName)
{
cout << "Found " << searchName << "!";
// s[i]->print();
break;
}
else
{
cout << "No records for student: " << searchName;
cout << "nEnter student name to search for. [ENTER] terminates" << endl;
cin >> searchName;
}
}
}
}
如何搜索用户从程序中输入的名称?
使用std::find_if
:
auto it = std::find_if(s.begin(),
s.end(),
[&searchName](const clsStudent* student)
{ return student->getName() == searchName; });
if (it != s.end()) {
// name was found, access element via *it or it->
else {
// name not found
}
C++03版本:
struct MatchName
{
MatchName(const std::string& searchName) : s_(searchName) {}
bool operator()(const clsStudent* student) const
{
return student->getName() == s_;
}
private:
std::string s_;
};
vector<clsStudent*>::iterator it = std::find_if(s.begin(),
s.end(),
MatchName(searchName));
// as before
因为如果找到了学生,则打印名称,然后中断for
-循环,并且当重新评估while
条件时,由于searchName
没有更改,该条件仍然为true。您应该将searchName
设置为长度为0的字符串,或者使用其他条件来中断while
。
由于条件while(searchName.length() != 0)
仍然有效,应用程序会连续打印结果。当您编写break
时,您会突破for循环for (int i = 0; i < s.size(); i++)
。例如:
while (true) {
for (;;) {
std::cout << "I get printed forever, because while keeps calling this for loop!" << std::endl;
break;
}
// Calling break inside the for loop arrives here
std::cout << "I get printed forever, because while's condition is always true!" << std::endl;
}
如果你试图允许用户不断搜索学生集合(即"找到/没有找到学生,找到另一个?"),你需要包括这些行。。。
cout << "nEnter student name to search for. [ENTER] terminates" << endl;
cin >> searchName;
在while循环中,以便修改searchName
并提示用户空输入将导致程序退出。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- 正在尝试重载二进制搜索树分配运算符
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- 如何在动态数组上使用搜索函数
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- cmake:添加要搜索头文件的目录
- 使用C++创建特殊的二叉搜索树
- 在C++的字符串中搜索和删除某些字符
- std::unordered_map 搜索算法是如何实现的?
- 使用不变量来确定二分搜索中的边界条件
- 二叉搜索如何比线性搜索更快?
- 按边长度递归搜索图中所有可行路径
- QStackWidget - 按名称搜索
- 在递归二叉搜索树中搜索
- 我的二进制搜索程序只是关闭了