2011-03-31 73 views
1

以下數組在C中給出++代碼:在C++中使用運營商排序字符串<

char strings[105][105]; 

什麼是寫operator<使用STLsort函數的字符串進行排序正確的方式是有可能呢?

+0

這看起來像一個家庭作業問題可疑。 – Mihai 2011-03-31 20:38:55

+1

爲什麼你會使用字符數組的stl排序?不使用std :: strings? – Tim 2011-03-31 20:39:31

+1

什麼字符串。我沒有看到任何字符串(只是一個大(2-D)字符數組)。 – 2011-03-31 20:40:58

回答

1

你不能重載operator<爲指針,但你不需要,因爲std :: sort可以接受任何比較函數(或函子)。

另一個問題是排序算法不能交換數組,因爲它們是不可分配的。但是,您可以將一個指針數組排序到二維數組中(原樣保留原始數組)。

#include <algorithm> 
#include <cstring> 
#include <cstdio> 

bool compare_cstring(const char* a, const char* b) 
{ 
    return strcmp(a, b) < 0; 
} 

int main() 
{ 
    const int count = 5; 
    char strings[count][10] = { "One", "Two", "Three", "Four", "Five" }; 
    char* sorted_view[count]; 
    for (int i = 0; i != count; ++i) { 
     sorted_view[i] = strings[i]; 
    } 

    std::sort(sorted_view, sorted_view + count, compare_cstring); 
    for (int i = 0; i != count; ++i) { 
     puts(sorted_view[i]); 
    } 
} 
3

無法編寫operator<char陣列配合使用。

4

該代碼實際上看起來像C代碼可疑,而不是使用std::string的C++。

沒有辦法編寫operator<,它將與std::sort一起使用,因爲沒有交換功能可以正常工作,除非您編寫該TOO。

使用std::string將使這很瑣碎,否則你就必須編寫自己的operator<(看看C函數strcmp)和swap功能。

編輯:請注意,交換std::string s幾乎肯定會比在char陣列中交換大量內存更快。

+0

目標是使用STL中的'sort'函數,這是C中不可用的。由於迭代器的工作方式,這可能是不可能的。 'std :: string'提供了我想避免的不必要的開銷。在'struct'中包裝字符數組提供了一種使用'sort'函數重載'operator <'結構的方法。想知道是否有更多方法使用'sort'對字符數組進行排序。 – Leonid 2011-03-31 20:52:48

+2

@Leonid你是否描述並顯示'std :: string'和你想象的一樣慢並且是你應用程序中的一個實際瓶頸?更簡單的程序(例如使用'string'等抽象類型)奇怪地傾向於執行更好,因爲您可以專注於高級算法而不是低級細節。 – 2011-03-31 20:56:26

+0

在我的情況'std :: string'將不得不做動態內存分配,我想避免使用靜態字符數組。對於**這個問題的目的,我根本不好奇找到哪一個更快。我很想知道是否可以在字符數組上使用'sort'。 – Leonid 2011-03-31 20:59:01

2

假設你真的需要排序的二維數組行明智的,這是一個有點困難,使std::sort()爲你做這個,即使考慮工作比較器仿函數:那就需要某種形式的迭代器適配器。

但是,您可以輕鬆地使用其他就地排序算法,如選擇排序:

#include <iostream> 
#include <algorithm> 
#include <string> 

template<int N> 
bool char_array_less(const char(&l)[N], const char(&r)[N]) 
{ 
    return std::char_traits<char>::compare(&l[0], &r[0], N) < 0; 
// for a more general solution 
// return std::lexicographical_compare(&l[0], &l[0]+N, &r[0], &r[0]+N); 
} 

template<int N> 
void swap_char_arrays(char(*l)[N], char(*r)[N]) 
{ 
    std::swap_ranges(&(*l)[0], &(*l)[0]+N, &(*r)[0]); 
} 

const int ROWS = 105; 
const int COLS = 105; 
int main() 
{ 
    char a[ROWS][COLS] = {"foo", "bar", "whatever" }; 

    for(char(*i)[COLS] = a; i != a+ROWS; ++i) 
     swap_char_arrays(i, 
         std::min_element(i, a+ROWS, char_array_less<COLS>)); 

    for(int i=0; i<ROWS; ++i) 
     std::cout << a[i] << '\n'; 
} 

試運行:https://ideone.com/15hRB