我有一个由两个 vector 数组组成的结构。
struct hotel {
vector<int> start_time[1000],end_time[1000];
};
我必须根据start_time
以end_time
的方式对结构进行排序。
例如,
start_time[0] has 4 elements:
start_time[0] = 12 10 8 9
end_time[0] = 100 20 30 50
start_time[1] has 5 elements:
start_time[1] = 100 23 50 10 32
end_time[1] = 40 20 10 15 34
所以输出将是:
start_time[0] = 8 9 10 12
end_time[0] = 30 50 20 100
start_time[1] = 10 23 32 50 100
end_time[1] = 15 20 34 10 40
请在这方面指导我。
谢谢
我发现了另外一件事,如果我没有声明 vector 数组,而是使用这个:
struct hotel {
vector<int> start_time,end_time;
}h[1000];
也将服务于我的目的,但现在我有 h[0] 而不是 start_time[0] 和 end_time[0]。 但是有同样的问题如何排序 h[i].start_time 而不是 h[i].end_time。 我试图像托尼的解决方案一样思考,使用对。 感谢您的回复。
最佳答案
#include <algorithm>
// create a container storing associated pairs of start and end times...
std::vector<std::pair<int,int>> times;
for (int v = 0; v < 1000; ++v) // vector to be ordered on this iteration...
{
assert(my_hotel.start_time[v].size() == my_hotel.end_time[v].size());
// populate times...
for (int i = 0; i < my_hotel.start_time[v].size(); ++i)
times.push_back(std::make_pair(my_hotel.start_time[v][i], my_hotel.end_time[v][i]));
// sort it...
std::sort(times.begin(), times.end());
// copy sorted data back into hotel structure...
for (int i = 0; i < times.size(); ++i)
{
my_hotel.start_time[v][i] = times[i].first;
my_hotel.end_time[v][i] = times[i].second;
}
times.clear();
}
以上内容可以更明确地完成,例如std::copy
和 lambda,但我个人认为这样做没有多大值(value)。
关于c++ - 根据第一个 vector 元素对结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20943648/