Reputation: 907
The problem is how to arrange order if i just used CStringArray
not CSortStringArray
the arrangement of first array sortarray is from (a to m) in order. But if i used CSortStringArray
still the arrangement is same. And second array sortarray1 from 1.txt to 15.txt the order is always wrong either using CStringArray
or CSortStringArray
?
void CtestmfcDlg::OnBnClickedOk()
{
CSortStringArray sortArray;
sortArray.Add(CString("a"));
sortArray.Add(CString("b"));
sortArray.Add(CString("c"));
sortArray.Add(CString("d"));
sortArray.Add(CString("e"));
sortArray.Add(CString("f"));
sortArray.Add(CString("g"));
sortArray.Add(CString("h"));
sortArray.Add(CString("i"));
sortArray.Add(CString("j"));
sortArray.Add(CString("k"));
sortArray.Add(CString("l"));
sortArray.Add(CString("m"));
CSortStringArray sortArray1;
sortArray1.Add(CString("1.txt"));
sortArray1.Add(CString("2.txt"));
sortArray1.Add(CString("3.txt"));
sortArray1.Add(CString("4.txt"));
sortArray1.Add(CString("5.txt"));
sortArray1.Add(CString("6.txt"));
sortArray1.Add(CString("7.txt"));
sortArray1.Add(CString("8.txt"));
sortArray1.Add(CString("9.txt"));
sortArray1.Add(CString("10.txt"));
sortArray1.Add(CString("11.txt"));
sortArray1.Add(CString("12.txt"));
sortArray1.Add(CString("13.txt"));
sortArray1.Add(CString("14.txt"));
sortArray1.Add(CString("15.txt"));
for (int i = 0; i <= sortArray.GetUpperBound(); i++)
{
testbox1.AddString(sortArray[i]);
}
//sortArray.Sort();
for (int j = 0; j <= sortArray1.GetUpperBound(); j++)
{
testbox2.AddString(sortArray1[j]);
}
}
Upvotes: 2
Views: 1189
Reputation: 31629
If minimum system requirement is Vista or higher then you can use CompareStringEx
.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "windows.h"
using namespace std;
int wmain()
{
vector<wstring> sa;
wchar_t temp[50];
for (int i = 12; i > 0; i--)
{
wsprintf(temp, L"%d.txt", i);
sa.push_back(temp);
}
struct {
bool operator()(const wstring &a, const wstring &b) {
return CompareStringEx(0, SORT_DIGITSASNUMBERS,
a.c_str(), a.length(), b.c_str(), b.length(), 0, 0, 0) == CSTR_LESS_THAN;
}
} mysort;
sort(sa.begin(), sa.end(), mysort);
for (size_t i = 0, count = sa.size(); i < count; i++)
wcout << sa[i] << endl;
return 0;
}
output:
1.txt
2.txt
3.txt
...
9.txt
10.txt
11.txt
12.txt
Upvotes: 1
Reputation: 3995
You cannot expect from a String sorting algorithm that it sorts Integers.
Filename 10.txt
will return at position [0] compared to 2.txt
that it is smaller (see ascii code 49 < 50).
If you want to sort by Integers and not Strings, you have to implement your own sort algorithm.
//To remove the last extension for a file you could use this:
std::string RemoveLastExtension(const std::string &fileName)
{
auto pos = fileName.rfind(".");
if (pos == std::string::npos)
pos = -1;
return std::string(fileName.begin(), fileName.begin() + pos);
}
Upvotes: 1