I'm teaching myself C++/CLR using Visual C++ 2008 (I'm so new I'm not too sure how even to phrase that all) and just as soon as I think I understand something it turns around and bites me.
I have a class that looks like this:
public ref class TABLE_KeyData{
public:
String^ myKey;
String^ myData;
public:
~TABLE_KeyData(){
}
TABLE_KeyData( String^ strKey, String^ strData ){
this->myKey = strKey;
this->myData = strData;
}
property
String^ Key{
String^ get(){
return myKey;
}
}
property
String^ Data{
String^ get(){
return myData;
}
}
};
And I've written a comparer for it that looks like this:
public ref class TABLE_KeyDataComparer: IComparer<TABLE_KeyData^>{
public:
virtual int Compare(TABLE_KeyData^ x, TABLE_KeyData^ y){
if (x == nullptr){
if (y == nullptr){
// If x is null and y is null, they're equal.
return 0;
}
else{
// If x is null and y is not null, y is greater.
return -1;
}
}
else{
// If x is not null...
if (y == nullptr){
// ...and y is null, x is greater.
return 1;
}
else{
String^ XStr;
String^ YStr;
XStr = x->myKey;
YStr = y->myKey;
return XStr->CompareTo(YStr);
}
}
}
};
(Heavily plagiarised I might add from msdn.microsoft!)
What I want it to do is sort:
Key Data
CD ZZZZ
AB YYYY
EF XXXX
to:
Key Data
AB YYYY
CD ZZZZ
EF XXXX
This is primarily so I can call the List->BinarySearch to find an entry so my code in main looks something like:
List<TABLE_KeyData^>^ Alpha_KeyData;
List<TABLE_KeyData^>^ Beta_KeyData;
.
.
.
<Fill both Alpha_KeyData & Beta_KeyData>
.
.
.
KeyCompare = gcnew TABLE_KeyDataComparer();
Alpha_KeyData->Sort(KeyCompare);
Beta_KeyData->Sort(KeyCompare);
AlphaFieldCount = Alpha_KeyData->Count;
for(AlphaFieldCounter = 0; AlphaFieldCounter < AlphaFieldCount; AlphaFieldCounter++){
BetaFieldCounter = Beta_KeyData->BinarySearch(Alpha_KeyData[AlphaFieldCounter], KeyCompare);
The BinarySearch doesn't seem to be working as it always returns a negative number.
Questions:
1. Is my comparer doing what it should on the sort?
2. Can I use the same one on the BinarySearch or do I need to write a separate one and if so how would it differ?
3. Is my call to BinarySearch correct?
Any help would be appreciated.