2

我有一个二维字符数组,在每一行中我存储一个名称......例如:

J O H N
P E T E R
S T E P H E N
A R N O L D
J A C K

我应该如何对数组进行排序以便最终得到

A R N O L D
J A C K
J O H N
P E T E R
S T E P H E N

这是一个二维字符数组.....没有字符串或字符点......

4

3 回答 3

2
#define MAX_NAME 8

char names[][MAX_NAME] = {"JOHN", "PETER", "STEPHEN", "ARNOLD", "JACK"};
 // strcmp is really (int (*)(const char *, const char *)), so we cast.
qsort(names, sizeof(names) / MAX_NAME, MAX_NAME, 
  (int (*)(const void *, const void *)) strcmp);

请注意,这可能不是冒泡排序。

于 2010-05-10T03:35:46.740 回答
0

C++ 不支持复制或比较 C 风格的数组,但它支持对包装非常薄的 C 风格的数组进行此类操作。Try ,这与C++0xboost::array中的 and 相同。tr1::arraystd::array

或者,自己动手:

#include <algorithm>

template< class T, size_t s >
struct array {
    T arr[s]; // public data, no destructor, inheritance, virtuals, etc
              // => type is aggregate
    operator T const *() const { return arr; }
    operator T *() { return arr; } // as close as we can get to array emulation

    friend bool operator< ( array const &l, array const &r )
        { return std::lexicographical_compare( l, l+s, r, r+s ); }
};

array< char, 10 > names[] // aggregate initialization — this is standard C++
    = { "JOHN", "PETER", "ARNOLD", "JACK" };

#include <iostream>
using namespace std;

int main() {
sort( names, names + sizeof names / sizeof *names );

for ( array<char,10> *s = names; s != names + sizeof names/sizeof*names; ++ s )
    cerr << *s << endl;
}

如果您的编译器没有疯狂地向上述结构添加填充,您可以安全地reinterpret_cast使用 C 样式数组 an array

template< class T, size_t s >
array< T, s > &wrap_arr( T (&a)[s] ) {
    return reinterpret_cast< array<T,s> & >( a );

        // make sure the compiler isn't really wacky...
        // I would call this optional:
    BOOST_STATIC_ASSERT( sizeof( T[s] ) == sizeof( array<T,s> ) );
}

char names_c[][10] // or whatever C input from wherever
    = { "JOHN", "PETER", "ARNOLD", "JACK" };

array<char, 10> *names = &wrap_arr( names_c[0] );
于 2010-05-10T03:59:03.680 回答
0

不要冒泡排序 - 第 1 点。

第二点:

比较每个子数组的第一个字符(即数组[x][0])是否需要移动,然后使用while循环移动子数组x中的所有字符......或保存子数组并移动它像那样...

于 2010-05-10T03:31:19.820 回答