【问题标题】:Binary search with vector c++使用向量c ++进行二分搜索
【发布时间】:2020-12-16 05:30:29
【问题描述】:

我有一个结构,其中数据定义为:

typedef struct contacts 
{
    string name;   //{jhonathan , anderson , felicia}
    string nickName; //{jhonny  , andy , felic}
    string phoneNumber; // {13453514 ,148039 , 328490}
    string carrier;  // {atandt , coolmobiles , atandt }
    string address; // {1bcd , gfhs ,jhtd }

} contactDetails;

vector <contactDetails> proContactFile;

在这里我想对name进行二进制搜索。如果搜索到的名称可用,那么我想显示该名称的相关联系方式(nickname,phone number ,carrier ,address)。我该怎么做?

【问题讨论】:

  • 为什么不使用关联容器,例如std::map&lt;std::string, contactDetails&gt;

标签: c++ vector struct binary-search


【解决方案1】:
auto cmpFn = [](const contacts &c1, const contacts &c2) {return c1.name < c2.name;};

// 1. vector must be sorted
std::sort(proContactFile.begin(), proContactFile.end(), cmpFn);

// 2. what to find
contacts findme; findme.name = "cat";

// 3. find
auto it = std::lower_bound(proContactFile.begin(), proContactFile.end(), findme, cmpFn);
bool found = it != proContactFile.end() && it->name == findme.name;

【讨论】:

  • 是的,这是有效的。但这不是冒泡排序??我需要使用冒泡排序搜索名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
  • 2021-11-30
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多