MRM
MRM

Reputation: 569

CString array sort

How can i sort (ascending or descending) an array of CString's? I saw a lot of references to std::vector, but i can't find an example of converting a CString array to a vector.

Upvotes: 1

Views: 10160

Answers (3)

user93353
user93353

Reputation: 14039

If you want to sort a CList, you can take a look at this.

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145389

Assuming that CString means ATL/MFC CString, complete demo program using std::sort to sort a raw array:

#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;
    }
}

Using a std::vector instead of a raw array is a little bit more intricate, since Visual C++’s standard library implementation does not yet support std::initialiser_list per version 11.0. In the example below I use a raw array to provide the data (this is an example of converting a CString array to a std::vector, as you ask for). But the data could conceivably come from any source, e.g. reading the strings from a file:

#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;
    }
}

As you can see, there is no difference in how the std::vector is used, compared to the raw array. At least at this level of abstraction. It's just more safe and with more rich functionality, compared to the raw array.

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409384

Since the CString class have an operator< you should be able to use std::sort:

CString myArray[10];

// Populate array

std::sort(myArray, myArray + 10);

Upvotes: 4

Related Questions