【发布时间】:2014-05-24 13:02:47
【问题描述】:
我一直在寻找有关此主题的更多信息,但似乎找不到我正在寻找的答案,所以希望您能提供帮助!
我正在处理的部分任务是编写一个程序来搜索字符串数组(地址簿),如果找到完全或部分匹配项,则返回匹配项。我可以使用 C 字符串数组轻松完成此操作,strstr() 函数通过 for 循环运行,并将指针设置为将用户输入关键字运行到数组中的结果(见下文)。
我的问题是,如果有的话,我将如何利用 String 对象来做到这一点?我还需要考虑到不止一种可能的匹配。这也是执行该程序的最有效方法吗?我已经提交了我的工作版本,我只是好奇其他一些方法可以完成同样的任务!
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
bool isFound = false; // Flag to indicate whether contact is found
const int SIZE = 11; // Size of contacts array
const int MAX = 50; // Maximum characters per row
char contacts[SIZE][MAX] = {
"Jig Sawyer, 555-1223",
"Michael Meyers, 555-0097",
"Jason Vorhees, 555-8787",
"Norman Bates, 555-1212",
"Count Dracula, 555-8878",
"Samara Moran, 555-0998",
"Hannibal Lector, 555-8712",
"Freddy Krueger, 555-7676",
"Leather Face, 555-9037",
"George H Bush, 555-4939",
"George W Bush, 555-2783"
};
char *ptr = NULL; // Pointer to search string within contacts
char input[MAX]; // User search input string
// Get the user input
cout << "Please enter a contact to lookup in the address book: ";
cin.getline(input,MAX);
// Lookup contact(s)
for (int i=0; i<SIZE; i++)
{
ptr = strstr(contacts[i], input);
if (ptr != NULL)
{
cout << contacts[i] << endl;
isFound = true;
}
}
// Display error message if no matches found
if (!contactFound)
cout << "No contacts found." << endl;
return 0;
}
如你所知,我喜欢恐怖片 :)
【问题讨论】:
-
My question is, how would I be able to do this, if at all, utilizing String objects?首先问问自己可以使用什么算法或数据结构来进行高效搜索。无论您是否使用字符串都不应该在这个初始点发挥作用。 -
我不确定它是否有预制函数,但
boost::adaptors::filtered带有一个短 lambda 使得这很容易。 -
啊,没提-第二学期的CS学生。下学期的数据结构和算法。我使用 C-String 方法只是因为我在进入 C++ 之前学习了一些 C。显然这是一个非常小的列表,但如果我有 10K 条记录,我想走最有效的路线。
-
@bran.io 保持记录按名称排序然后进行二分搜索怎么样?
-
@bran.io - “下学期的数据结构和算法” - 听起来像是找到最有效的方法来徒手在大海捞针。甚至二分搜索也不行(正如 faranwath 建议的那样)?
标签: c++ arrays string search cstring