如何对CString数组进行排序(升序或降序)?我看到了很多对std::vector的引用,但我找不到一个将CString数组转换为向量的示例。
发布于 2012-11-16 22:37:28
假设CString表示ATL/MFC CString,使用std::sort完成对原始数组进行排序的演示程序:
#include <atlbase.h>
#include <atlstr.h>
#include <algorithm> // std::sort
#include <iostream> // std::wcout, std::endl
#include <utility> // std::begin, std::end
std::wostream& operator<<( std::wostream& stream, CString const& s )
{
return (stream << s.GetString());
}
int main()
{
using namespace std;
CString strings[] = { "Charlie", "Alfa", "Beta" };
sort( begin( strings ), end( strings ) );
for( auto&& s : strings )
{
wcout << s << endl;
}
}使用std::vector而不是原始数组有点复杂,因为Visual C++的标准库实现在11.0版中还不支持std::initialiser_list。在下面的示例中,我使用一个原始数组来提供数据(这是一个按照您的要求将CString数组转换为std::vector的示例)。但数据可能来自任何来源,例如从文件中读取字符串:
#include <atlbase.h>
#include <atlstr.h>
#include <algorithm> // std::sort
#include <iostream> // std::wcout, std::endl
#include <utility> // std::begin, std::end
#include <vector> // std::vector
std::wostream& operator<<( std::wostream& stream, CString const& s )
{
return (stream << s.GetString());
}
int main()
{
using namespace std;
char const* const stringData[] = { "Charlie", "Alfa", "Beta" };
vector<CString> strings( begin( stringData ), end( stringData ) );
sort( begin( strings ), end( strings ) );
for( auto&& s : strings )
{
wcout << s << endl;
}
}如您所见,与原始数组相比,std::vector的使用方式没有什么不同。至少在这个抽象层次上是这样。与原始数组相比,它更安全,功能更丰富。
发布于 2012-11-16 22:22:20
因为CString类有一个operator<,所以您应该能够使用std::sort
CString myArray[10];
// Populate array
std::sort(myArray, myArray + 10);发布于 2012-11-16 23:03:49
如果你想对一个CList进行排序,你可以看看this。
https://stackoverflow.com/questions/13418372
复制相似问题