如何减少执行时间?
这是一个函数的代码片段,该函数采用字符串向量(客户姓名向量)并需要查找以某种频率出现的名称。如何让它运行得更快(快于 2 秒,尤其是处理较大的数据集时)。该函数是程序的所有功能。
提前致谢。
vector<string> most_active(vector<string> &customers) {
vector<string> result;
double p = (double)customers.size()*5/100;
for(string &customer: customers) {
if(find(result.begin(), result.end(), customer) != result.end())
continue;
if(count(customers.begin(), customers.end(), customer) >= p)
result.push_back(customer);
}
sort(result.begin(), result.end());
return result;
}
我尝试通过引用传递数据而不是通过值传递数据,但这没有帮助
Here is a code snippet of a function that takes vector of strings (vector of customer names) and need to find names which occurs with some frequency. How to make it run faster (faster than 2 seconds especially operating with larger sets of data). This function is the all functionality of a program.
Thanks in advance.
vector<string> most_active(vector<string> &customers) {
vector<string> result;
double p = (double)customers.size()*5/100;
for(string &customer: customers) {
if(find(result.begin(), result.end(), customer) != result.end())
continue;
if(count(customers.begin(), customers.end(), customer) >= p)
result.push_back(customer);
}
sort(result.begin(), result.end());
return result;
}
I tried to pass data by reference instead of passing by value, but it didn't help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来
result
应该是std::set
因为您希望保持数据有序并且不希望有任何重复项。这需要您的 O(n²) 算法并使其成为 O(n log(n))。It looks like
result
should be astd::set
since you want to keep the data ordered and you don't want any duplicates. This takes your O(n²) algorithm and makes it O(n log(n)).