Sunday, April 3, 2011

string cannot be allocated by "malloc"

string cannot be allocated by "malloc".the only way to allocate memory for string is to "new" one.

string test=new string;

"segment fault" in sort function

When I used "sort" (STL/Algorithm) to sort my own "struct", I need define my own compare function.


bool custom_sort(Var const& lhs, Var const& rhs)
{
    if (lhs.weight != rhs.weight)
        return lhs.weight < rhs.weight;
    return true;
}
 then call it:

 sort(sort_var.begin(), sort_var.end(), &custom_sort);

Then I sometimes got an error message:
Segment fault.
The problem is caused by ignoring the following fact:
In C++, your "compare" predicate must be a strict weak ordering. In particular, "compare(X,X)" must return "false" for any X. While in my case, I always return a "true" when the variables are equal to each other. Therefore, this "compare" predicate does not impose a strict weak ordering, and the result of passing it to "sort" is undefined. 
So solution:
The right action to handle two equal variables is to "return false" not "return true".