繁体   English   中英

二进制搜索和按字母顺序对数组排序C ++

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM