Sign in to follow this  
floatingwoods

std::sort corrupts my memory

Recommended Posts

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?

 

 

Share this post


Link to post
Share on other sites
[tt]SMyStruct::operator<[/tt] 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... Edited by fastcall22

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this