std::sort corrupts my memory

Started by
5 comments, last by Ryan_001 8 years ago

Hello,

I have a strange behaviour I can't explain. I have this structure:


struct SMyStruct {
    int x;
    int y;
    bool operator< (const SMyStruct& m) const {return true;}
};

with following code:



std::vector<std::pair<float,SMyStruct > > items;
for (size_t i=0;i<8;i++)
{
    SMyStruct a;
    a.x=i;
    for (size_t j=0;j<8;j++)
    {
        a.y=j;
        items.push_back(std::make_pair(0.0,a));
    }
}

std::sort(items.begin(),items.end());

for (size_t i=0;i<items.size();i++)
{
    int x=items[i].second.x;
    int y=items[i].second.y;
    printf("i: %i --> %i, %i\n",i,x,y);
}

The above code was simplified, but the idea is to basically sort items according to a float value (in above code that float value is always 0.0). Above will corrupt my memory and later crash. Also, the output is mostly correct, but sometimes I get very large, non-logical values for x and y, after the sort. I can't figure out where I made a mistake. But I can fix that strange behaviour by having the comparison operation of the struct always return false instead of true (since I only care about sorting according to the float value of the pair I can return true or false).

Can anyone see where there is a bug in above code?

Advertisement
SMyStruct::operator< is an invalid comparator. Write a well formed comparator for SMyStruct to fix:

bool SMyStruct::operator< ( const SMyStruct& m ) const {
    return std::tie(x, y) < std::tie(m.x, m.y); 
}

// or 

bool SMyStruct::operator< ( const SMyStruct& m ) const {
    if ( x < m.x )  return true;
    if ( x > m.x )  return false;
    if ( y < m.y )  return true;
    return false;
}

(Also note that this is the typical implementation of operator< for tuples and pairs.)


What compiler are you using? I can’t remember the last time anybody’s needed to add whitespace between right angle brackets in a template typename...
Your std::sort predicate is invalid - Googling for "std::sort invalid predicate" will explain why this is a bad idea.

Thanks to both of you, that makes perfect sense in hindsight!

Oh, forgot to mention: I am using MinGW

Then you either use an extremely ancient version of the compiler or you can just write
std::vector<std::pair<float,SMyStruct>>
without extra spaces between template closing brackets.

What compiler are you using? I can’t remember the last time anybody’s needed to add whitespace between right angle brackets in a template typename...

I know for myself adding the space just became a habit.

This topic is closed to new replies.

Advertisement