简体   繁体   中英

C++ using std::sort for multi dimensional array of strings

I have an array of strings string relationarray[10000][2];

taken from #include<string> . Every string at relationarray[index][0] of the array has a 4 digit number at its beginning that I'm trying to use to sort the array. The array is usually not full.

from #include<algorithm> I'm trying to use

std::sort(relationarray,relationarray + (sizeof(relationarray)/sizeof(relationarray[0])) to get eveyrthing in order. but sort puts the strings at the end of the array in favor of null positions. What am I doing wrong? I tried creating comparison function for the third argument of sort but it doesn't compile.

bool waytosort(string one, string two){
if (two.empty()){
    return false;
}
int first =stoi(one.substr(0,3));
int second=stoi(two.substr(0,3));
return first<second;

}

uncletall has the right idea--putting the strings into a struct--but there's no need to abandon <algorithm> for nasty legacy C code.

#include <algorithm>
#include <stddef.h>

struct MyData {
    string code;
    string name;

    bool operator <(const MyData& rhs) const
    { return (rhs.code == "") || ((code != "") && (code < rhs.code)); }
};

static const size_t kNumElements = 100000;
MyData* data[kNumElements];

sort(data, data + kNumElements);

The only magic here is defining an operator< for the new struct that sorts by the first string, and orders empty strings to the end instead of the start. Since you say the array isn't always full (IMHO you really should be using std::vector here), it would be better if you kept track of how many elements were in the array and used it to generate the end iterator.

I would suggest you use a struct for your data:

typedef struct {
    string code;
    string name;
} my_data;

int compare_my_data(const void *p1, const void *p2)
{
    const my_data *e1 = reinterpret_cast<const my_data*>(p1);
    const my_data *e2 = reinterpret_cast<const my_data*>(p2);
    return e1->code.compare(e2->code);
}

my_data mydata[100000];
std::qsort(mydata, 10000, sizeof(mydata), compare_my_data);

This should give you enough to come up with your own solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM