我有一个基于变量排序的Vector结构。
例如:
struct Client {
string name;
int sm_index;
int client_id;
int user_id;
Client(string str, int x, int y, int c) : name(str), sm_index(x), client_id(y),user_id(c){}
}
根据 sm_index
进行排序如何查找和获取sm_index与目标结构匹配的结构数据。
我们有下面的矢量,没有。结构加入其中。
例如:
vector <client> CLIENT;
CLIENT.push_back(Client("Rahul",8,1,13));
CLIENT.push_back (Client("Sahil",12,3,12));
CLIENT.push_back (Client("Ramesh",1,4,11));
CLIENT.push_back (Client("Suresh",5,5,10));
CLIENT.push_back (Client("Ganesh",86,6,9));
CLIENT.push_back (Client("Gagan",4,7,8));
如何找到sm_index值等于5的结构。
我尝试了find()函数,但无法理解如何使用它。
答案 0 :(得分:1)
基于Yola,这是一个现成的代码片段
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
struct Client {
std::string name;
int sm_index;
int client_id;
int user_id;
Client(std::string str, int x, int y, int c)
: name(str), sm_index(x), client_id(y), user_id(c)
{}
};
int main()
{
std::vector<Client> CLIENT;
CLIENT.push_back(Client("Rahul",8,1,13));
CLIENT.push_back(Client("Sahil",12,3,12));
CLIENT.push_back(Client("Ramesh",1,4,11));
CLIENT.push_back(Client("Suresh",5,5,10));
CLIENT.push_back(Client("Ganesh",86,6,9));
CLIENT.push_back(Client("Gagan",4,7,8));
auto it = std::find_if(CLIENT.begin(), CLIENT.end(),[](const Client& v) {
return v.sm_index == 8;
});
if (it != CLIENT.end())
{
std::cout << (*it).name << "\n";
}
}
答案 1 :(得分:0)
如果您的std::vector
按sm_index
排序,则您可以使用二进制搜索来查找与sm_index
匹配的元素。这比std::find_if
快。
C ++标准库提供了一些用于二进制搜索的算法。 std::equal_range
可用于查找匹配sm_index
的多个元素,但如果您只想找到一个匹配sm_index
的元素,则可以使用std::lower_bound
:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
struct Client {
std::string name;
int sm_index;
int client_id;
int user_id;
Client(std::string str, int x, int y, int c)
: name(str), sm_index(x), client_id(y), user_id(c)
{}
bool operator<(const Client& a) const { return sm_index < a.sm_index; }
};
int main() {
std::vector<Client> CLIENT;
CLIENT.push_back(Client("Rahul",8,1,13));
CLIENT.push_back(Client("Sahil",12,3,12));
CLIENT.push_back(Client("Ramesh",1,4,11));
CLIENT.push_back(Client("Suresh",5,5,10));
CLIENT.push_back(Client("Ganesh",86,6,9));
CLIENT.push_back(Client("Gagan",4,7,8));
std::sort(CLIENT.begin(), CLIENT.end());
Client target("", 5, 0, 0);
std::vector<Client>::iterator it = std::lower_bound(CLIENT.begin(), CLIENT.end(), target);
if (it != CLIENT.end()) {
std::cout << it->name << "\n";
}
}
答案 2 :(得分:-1)
您可以通过迭代向量并比较属性来实现。我想你不是在寻找优化程序。
for( auto iter = CLIENT.begin(); iter != CLIENT.end() ; iter++ )
{
if( iter->sm_index == 5 ) // compare attribute for your structure
std::cout << " Found" << std::endl;
}
<强>被修改强>
使用std::binary_search
这是一种更快捷的方法。
Client target("",0, 5, 0);
bool found = std::binary_search( CLIENT.begin(), CLIENT.end(), target, []( Client a, Client b ){ return a.client_id < b.client_id; } );
found ? std::cout << "Found" << std::endl : std::cout << "Not found" << std::endl;