[英]Binary Search and Sorting an Array by alphabetical order C++
我有一個動態數組,其中包含聯系電話和姓名。 我想知道如何對名稱進行二進制搜索。 假設我有20位聯系人,並且我想查找名稱為"John"
的聯系人的號碼。
這是數據結構:
struct Contact
{
int ContactNumber,Fax;
string Name, Email;
PhoneNumber Phone;
Address anAddress;
};
我有:
Contact * ptrFirst = & arrofCont[0];
Contact * ptrLast = & arrofCont[MAX - 1];
其中包含聯系人姓名,電話號碼和地址等。我想這些可以用作第一個和最后一個,但不知道從那里去哪里。
您無需對數組進行排序或二進制搜索即可完成所需的操作。
只需使用std::find_if
。
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Company
{
std::string name ;
std::string number ;
};
struct HasName
{
HasName (const std::string &name) : name (name) {}
bool operator () (const Company &company) {
return company.name == name ;
}
std::string name ;
};
int main (void)
{
std::vector <Company> companies ;
// Fill up the vector...
std::vector <Company>::const_iterator citer ;
citer = std::find_if (companies.cbegin (), companies.cend (), HasName ("John")) ;
if (citer != companies.cend ()) {
std::cout << citer->number << "\n" ;
}
return 0 ;
}
這是一個使用lambda表達式比較數組中的一對元素的示例。它對應於更新之前的原始帖子。
#include <iostream>
#include <algorithm>
#include <string>
struct Contact
{
std::string name;
int number;
};
int main()
{
const size_t N = 3; // or N = 20 or you can use name MAX instead of N
Contact *p = new Contact[N] { { "B", 2 }, { "A", 1 }, { "C", 3 } };
auto less_by_name = []( const Contact &c1, const Contact &c2 )
{
return ( c1.name < c2.name );
};
std::sort( p, p + N, less_by_name);
auto it = std::lower_bound( p, p + N, Contact( { "B", 0 } ), less_by_name );
if ( it != p + N ) std::cout << "The number of \"B\" is " << it->number << std::endl;
delete []p;
}
或者,您可以使函子成為班級的成員。 例如
#include <iostream>
#include <algorithm>
#include <string>
struct Contact
{
std::string name;
int number;
static bool less_by_name( const Contact &c1, const Contact &c2 )
{
return ( c1.name < c2.name );
}
};
int main()
{
const size_t N = 3; // or N = 20 or you can use name MAX instead of N
Contact *p = new Contact[N] { { "B", 2 }, { "A", 1 }, { "C", 3 } };
std::sort( p, p + N, Contact::less_by_name);
auto it = std::lower_bound( p, p + N, Contact( { "B", 0 } ), Contact::less_by_name );
if ( it != p + N ) std::cout << "The number of \"B\" is " << it->number << std::endl;
delete []p;
}
至於你的定義
Contact * ptrFirst = & arrofCont[0];
Contact * ptrLast = & arrofCont[MAX - 1];
那么如果您將通過以下方式更改它們
Contact * ptrFirst = arrofCont;
Contact * ptrLast = arrofCont + MAX;
然后它們將對應
Contact * ptrFirst = p;
Contact * ptrLast = p + N;
相對於我的代碼示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.