可以只使用std::sort
排序的矢量,並限定自定義比較算符(即與重載operator()
類)。
您可以將排序列的索引存儲在std::vector
(這將成爲自定義比較對象的「狀態」的一部分)中,並比較索引存儲在該向量中的列的字符串。
您可以在「排序列」向量的第一個索引中指定的列處開始比較值;如果它們相同,則繼續比較向量中下一個索引中指定的列處的值,這可以在比較器operator()
過載體內的for
循環內完成。
請看下面的代碼作爲一個例子(使用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
http://stackoverflow.com/questions/15183953/sorting-a-vector-multiple-times(今天同樣的問題由其他用戶提供) – 2013-03-03 12:48:03
我知道這個lhs和rhs的東西,但我不知道如何初始化lhs和rhs的矢量 。它應該是什麼?我有我所有的矢量字符串矢量> allInputs ;. –
user1375155
2013-03-03 13:05:04