【发布时间】:2021-07-15 08:36:27
【问题描述】:
我有一个std::list<struct Data> data。我需要根据rule 规则将data 按head 排序。
为此,我使用std::list::sort(Compare comp)。
下面的实现有效,但是效率低下。在rule列表中查找元素需要遍历列表,计算距离需要再次遍历列表。
数据还能如何排序?也许使用向量、unordered_map 等?
#include <iostream>
#include <list>
#include <algorithm>
struct Data {
std::string code;
std::string text;
std::string head;
};
int main() {
struct Data data1{"0010", "it is text1", "head3"};
struct Data data2{"0025", "it is text2", "head1"};
struct Data data3{"0065", "it is text3", "head2"};
struct Data data4{"0011", "it is text4", "head2"};
std::list<struct Data> data = {data1, data2, data3, data4};
std::list<std::string> rule = {"head1", "head2", "head3", "head4"};
data.sort([&rule](const Data& first, const Data& second) {
auto index_a = std::distance(rule.begin(), std::find(rule.begin(),rule.end(),first.head));
auto index_b = std::distance(rule.begin(), std::find(rule.begin(),rule.end(),second.head));
return index_a < index_b;
});
for (auto &it : data)
std::cout << it.code << "\t" << it.text << "\t" << it.head << "\n";
return 0;
}
【问题讨论】:
-
您能否详细说明您在使用该排序方法的效率时遇到的问题?
-
旁白:
std::list<struct Data>中不需要struct -
因为你需要随机访问列表
std::vector可能会给你更好的性能 -
@UlrichEckhardt,在规则列表中查找元素需要遍历列表,计算距离需要再次遍历列表。
-
请将其放入问题中,而不是作为评论!