您可以只使用std::sort
对向量进行排序,并定义一个自定义比较器函子(即具有重载的类operator()
)。
您可以将排序列的索引存储在 a 中std::vector
(这将是自定义比较器对象的“状态”的一部分),并比较索引存储在该向量中的列中的字符串。
您开始比较“排序列”向量中第一个索引中指定的列的值;如果它们相同,则继续比较向量中下一个索引中指定的列的值,等等。这可以在比较器重载for
主体内的循环内完成。operator()
以以下代码为例(使用 g++ (GCC) 4.7.2 编译):
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<vector<string>> BuildTestData()
{
vector<string> r1 = {"hello", "world", "1", "3", "4", "7", "2", "1"};
vector<string> r2 = {"world", "hello", "1", "4", "8", "4", "2", "1"};
vector<string> r3 = {"phone", "mouse", "2", "3", "5", "2", "1", "4"};
return vector<vector<string>>{r1, r2, r3};
}
void PrintData(const vector<vector<string>> & v)
{
for (size_t r = 0; r < v.size(); r++)
{
for (size_t c = 0; c < v[r].size(); c++)
cout << v[r][c] << ' ';
cout << '\n';
}
}
class StringListComparator
{
public:
explicit StringListComparator(vector<int> sortColumns)
: m_sortColumns( move(sortColumns) )
{
}
bool operator()(const vector<string>& lhs, const vector<string>& rhs) const
{
// For each sorting column:
for (size_t i = 0; i < m_sortColumns.size(); i++)
{
// Comparison with current column
const int currentColumn = m_sortColumns[i];
if (lhs[currentColumn] < rhs[currentColumn])
return true;
if (lhs[currentColumn] > rhs[currentColumn])
return false;
// lhs[currentColumn] == rhs[currentColumn],
// so check with next sorting column
}
return false;
}
private:
vector<int> m_sortColumns;
};
int main()
{
auto v = BuildTestData();
cout << "Before sorting:\n";
PrintData(v);
vector<int> sortColumns = {5, 7}; // indexes are 0-based
sort(v.begin(), v.end(), StringListComparator(sortColumns));
cout << "\nAfter sort:\n";
PrintData(v);
}
样品运行:
Before sorting:
hello world 1 3 4 7 2 1
world hello 1 4 8 4 2 1
phone mouse 2 3 5 2 1 4
After sort:
phone mouse 2 3 5 2 1 4
world hello 1 4 8 4 2 1
hello world 1 3 4 7 2 1