给定一个包含七种颜色的彩虹但按随机顺序排列的字符串数组,我不知何故应该按此顺序对此数组进行排序以输出红色,橙色,绿色,......,紫色.彩虹色的顺序.我该如何排序这个数组?
这段代码没有完成。但你应该有一个大概的了解。我跳过的一件事是整数本身的排序。既然它应该是微不足道的。正如您所看到的,映射有点 PIA,看起来很糟糕。但既然你禁止使用STL,就没有std::map
. N
此外,我暗示所有表的静态大小。它可以动态分配,没问题,也没有std::vector
。
我使用else if
s 表示map*
函数来模仿std::map
功能。可能switch ... case
可以使用,但它在一个像样的编译器上应该工作得几乎相同。
我在下面编写的代码在提供的功能方面与 Armen 的代码几乎相同。我会推荐他的解决方案。我跳过了相同的部分。所以你可以看到它更丑而且打字更多。它看起来几乎像纯 C 语言。如果您真的渴望在非常大的情况下提高速度,也许可以进行一点修改。这将使用一个临时数据结构来保存映射值,对其进行排序,然后将其映射回来。准确地说,我建议避免在高性能约束下调用map::operator[](const &T)
(或任何访问器)以避免哈希计算。std::string
但仅此而已。
还有一些需要讨论的内容。就像如果您希望两种颜色具有相同的值或使用非整数权重一样。基于 STL 的解决方案适应性更强。
/* This will map color literals (color names) to integers, which will associate them with
a numerical value, than can be used for comparison */
enum Colors { Red, Orange, Green, /*...*/ Violet };
/* this should read colors as std::string instances from the input array and assing
the the appropriate color codes into output array at corresponding indexes */
void mapString2Color( const std::string* input, int* output, size_t N ){
for(size_t i = 0; i < N; i++){
if ( input[i] == std::string("red") ) output[i] = Colors::Red;
else if ( input[i] == std::string("orange") ) { output[i] = Colors::Orange; }
else if ( input[i] == std::string("green") ) { output[i] = Colors::Green; }
/*...*/
else if ( input[i] == std::string("violet") ) { output[i] = Colors::Violet; }
else {/*unspecified color code */}
}
}
/* this is supposed to do the opposite to mapString (i.e. put appropriate
string at output[i] based on input[i]) */
void mapColor2String( const int* input, std::string* output, size_t N ){
for(size_t i = 0; i < N; i++){
if ( input[i] == Colors::Red ) output[i] = std::string("red");
else if ( input[i] == Colors::Orange ) { output[i] = std::string("orange"); }
else if ( input[i] == Colors::Green ) { output[i] = std::string("green"); }
/*...*/
else if ( input[i] == Colors::Violet ) { output[i] = std::string("violet"); }
else {/*unspecified color index*/}
}
}
void sort(int* array, size_t N){
/* any in-place sort of your liking for table of (unsigned) integers */
}
main(){
std::string[N] input_array;
std::string[N] output_array;
int[N] temp_array;
//map (translate) colors to their numerical values
mapString2Color(input_array, temp_array, N);
//sort it
sort(temp_array, N);
//map (translate) the values back to color names
mapColor2String(temp_array, output_array, N);
}
Run Code Online (Sandbox Code Playgroud)