c++ - 根据第一个 vector 元素对结构进行排序

标签 c++ sorting vector struct

我有一个由两个 vector 数组组成的结构。

struct hotel {
  vector<int> start_time[1000],end_time[1000];
};

我必须根据start_timeend_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/

相关文章:

c++ - WinCe PlaySound 不是每次都有效

c++ - 单链表c++构造函数、析构函数和打印

java - 有没有办法使用Java泛型类型来编写排序算法?

c++ - 如何从数组类中删除元素

c++ - 如何从 C++ 中的 vector 中删除节点

c++ - token 解析器语义操作

c++ - dyld:未加载库:在 OS X 上

java - 通过复杂对象结构深处的变量对列表进行排序

python - 根据 Python 中的自定义字母表对字符串值进行排序

php - 有没有一个好的 PHP 向量和矩阵库?