将“排序”与字符数组一起使用(C++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14111841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use 'sort' with char array(C++)
提问by Harish Vishwakarma
Is it possible to use 'sort' defined inside 'algorithm' for sorting char arrays according to their ASCII value? If yes, please provide an example.
是否可以使用在“算法”中定义的“排序”根据其 ASCII 值对字符数组进行排序?如果是,请举例说明。
回答by Nawaz
Yes. That is definitely possible. You could know that just by writing some sample code, such as this:
是的。那绝对是可能的。您可以通过编写一些示例代码来了解这一点,例如:
char charArray[] = {'A','Z', 'K', 'L' };
size_t arraySize = sizeof(charArray)/sizeof(*charArray);
std::sort(charArray, charArray+arraySize);
//print charArray : it will print all chars in ascending order.
By the way, you should avoidusing c-style arrays, and should prefer using std::array
or std::vector
.
顺便说一句,你应该避免使用 c 风格的数组,而应该更喜欢使用std::array
or std::vector
。
std::array
is used when you know the size at compile-time itself, while std::vector
is used when you need dynamic array whose size will be known at runtime.
std::array
当您在编译时知道大小时std::vector
使用,而当您需要在运行时知道大小的动态数组时使用。
回答by Oliver Charlesworth
Yes:
是的:
char array[] = "zabgqkzg";
std::sort(array, array+sizeof(array));
See http://ideone.com/0TkfDnfor a working demo.
有关工作演示,请参阅http://ideone.com/0TkfDn。
回答by Dietmar Kühl
The proper way is, of course, to use std::begin()
and std::end()
:
当然,正确的方法是使用std::begin()
and std::end()
:
std::sort(std::begin(array), std::end(array));
If you don't have a C++ 2011 compiler, you can implement corresponding begin()
and end()
functions, e.g.:
如果你没有 C++ 2011 编译器,你可以实现相应的begin()
和end()
函数,例如:
template <typename T, int Size>
T* end(T (&array)[Size]) {
return array + Size;
}
回答by Varun Garg
Answers using sizeof(charArray)
assume that the array must be completely filled. When ran using partially filled array, they produce garbage results.
使用的答案sizeof(charArray)
假设必须完全填充数组。当使用部分填充的数组运行时,它们会产生垃圾结果。
In that case use:
在这种情况下使用:
sort(str, str + strlen(str));