首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CString数组排序

CString数组排序
EN

Stack Overflow用户
提问于 2012-11-16 22:16:21
回答 3查看 8.9K关注 0票数 1

如何对CString数组进行排序(升序或降序)?我看到了很多对std::vector的引用,但我找不到一个将CString数组转换为向量的示例。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-16 22:37:28

假设CString表示ATL/MFC CString,使用std::sort完成对原始数组进行排序的演示程序:

代码语言:javascript
复制
#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的示例)。但数据可能来自任何来源,例如从文件中读取字符串:

代码语言:javascript
复制
#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的使用方式没有什么不同。至少在这个抽象层次上是这样。与原始数组相比,它更安全,功能更丰富。

票数 4
EN

Stack Overflow用户

发布于 2012-11-16 22:22:20

因为CString类有一个operator<,所以您应该能够使用std::sort

代码语言:javascript
复制
CString myArray[10];

// Populate array

std::sort(myArray, myArray + 10);
票数 4
EN

Stack Overflow用户

发布于 2012-11-16 23:03:49

如果你想对一个CList进行排序,你可以看看this

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13418372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档