2013-03-03 30 views
2

我想排序一個向量的字符串矢量,但我不明白如何創建一個比較函數。C++用比較器對字符串矢量的矢量進行排序。請幫我理解

我看到這個線程,但不能落實到我的情況: sorting vector of vector of strings in C++

,所以我有一個字符串看起來像這樣的矢量的矢量:
你好,世界,1,3,4,7,2 ,1個
世界,你好,1,4,8,4,2,1個
電話,鼠標,2,3,5,2,1,4-

我需要通過排序矢量串的這種載體我的用戶指定的列。我的用戶可以指定多個列進行排序。假設第3列和第5列。列3(1,1,2)對於第1行和第2列具有相同的值,那麼我們必須按第5列排序。爲了不使事情複雜化,這全部按升序排列。

我不明白當它傳遞給比較函數時它是如何工作的概念。我的函數如何在這些線程中的人員發佈的示例中循環?

無論如何,先謝謝了!

+2

http://stackoverflow.com/questions/15183953/sorting-a-vector-multiple-times(今天同樣的問題由其他用戶提供) – 2013-03-03 12:48:03

+0

我知道這個lhs和rhs的東西,但我不知道如何初始化lhs和rhs的矢量 。它應該是什麼?我有我所有的矢量字符串矢量> allInputs ;. – user1375155 2013-03-03 13:05:04

回答

3

可以只使用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 
+0

非常感謝。我現在明白了。謝謝!! – user1375155 2013-03-04 04:29:07

+0

@ user1375155:做一個好的StackOverflow公民:如果你發現這篇文章(以及其他人寫的其他文章)有用,請對它們進行投票並標記出最好的答案。 – 2013-03-04 08:27:28