我需要帮助制作数组列表。
我确实在Google上搜索了如何制作一个,但它们都很复杂。
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
int main() {
// First Name of person
string FirstName;
// Last Name of person
string LastName;
//List of names
string fstName = {"Max" , "Sasha" };
cout << "Search Name In Database" << endl;
cout << "First Name: ";
cin >> FirstName;
if (FirstName == fstName) {
cout << "Name Found!" << endl;
}
return 0;
}
[我希望我被问到“名称”,然后写Sasha,我希望它说“找到名称”,对Max来说也是一样。但是,在键入和输入时都找不到它们。
有两个大问题需要解决。最大的是知道==
运算符的实际作用。它检查两个对象之间的等效性。您正在使用它作为搜索非列表列表的方式。自然,字符串和列表永远不会彼此等同,它们是完全不同的类型。这导致第二件事。如果您想要一个列表,并且由于包含了标题,它看起来就是这样,则声明一个列表。
// I cut out lines that weren't pertinent to the example
#include <iostream>
#include <list>
int main() {
// First Name of person
std::string FirstName;
// Actual list of names
std::list<std::string> fstName = {"Max", "Sasha"};
std::cout << "Search Name In Database\nFirst Name: ";
std::cin >> FirstName;
// Manually check each item in list, exit if found. Very inefficient
for (auto i : fstName) {
if (i == FirstName) {
std::cout << "Name found!\n";
break;
}
}
return 0;
}
如果这仅是一项任务,则除非您自己列出列表,否则上面的代码可能会很好。如果是用于生产,建议您将STL放在较重的位置,并在填充列表后std::sort
-列出列表,并使用std::find
来查找项目。或依靠您可以使用的任何内部算法。
还有一个小问题:我删除了using namespace std;
。我曾经在入门课程中使用过它,而且我总是告诉学生,我只是想让他们不要沉迷于语法,但是如果我不再允许它,它将在下一门课程中适得其反。因此,现在完全不允许这样做。由于命名空间污染,这是一种不好的做法,从长远来看,这使您的代码更容易理解,因为您在阅读代码时会更好地了解类型和函数的来源。
这里使用更多的STL是不同的看法。我可以说是通过使用std::begin()
和std::end()
来了,但我只是喜欢它们的外观。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector> // vector instead of list for STL algorithms to play nice
int main() {
// First Name of person
std::string FirstName;
// List of names
std::vector<std::string> fstName = {"Max", "Sasha"};
// I realize the trivial list is already sorted, but this is how
// you could sort a much larger list that likely isn't in order
std::sort(std::begin(fstName), std::end(fstName));
std::cout << "Search Name In Database\nFirst Name: ";
std::cin >> FirstName;
auto location = std::find(std::begin(fstName), std::end(fstName), FirstName);
if (location != std::end(fstName))
std::cout << "Name Found!\n";
return 0;
}
[如果您发现自己在整个列表中进行了大量排序和查找,那么将您的时间包装在函数中是值得的,因此您只需提供相关信息,而不必总是提供[C0 ]和begin()
迭代器。