我有一个2d的字符数组,每行我存储一个名字......比如:
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
这是一个二维数组的字符.....没有字符串或字符点.....
答案 0 :(得分: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);
请注意,这可能不是冒泡排序。
答案 1 :(得分:0)
不要冒泡排序 - 点号1。
第二点:
比较每个子数组的第一个字符(即数组[x] [0])是否需要移位然后使用while循环移位子数组x中的所有字符...或者保存子阵列并将其移动......
答案 2 :(得分:0)
C ++不支持复制或比较C风格的数组,但它确实支持非常精简的C风格数组上的此类操作。试试boost::array
,它与C ++ 0x中的tr1::array
和std::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样式数组和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] );