Sort the struct in the vector container in STL

Source: Internet
Author: User

Sorting of int-type vector data is very simple, such as: vector <int> vectemp;

You can use the sort (vectemp. Begin (), vectemp. End () function. The default sorting is from small to large.

Note: The sort function requires the # include <algorithm> header file andUsing
NamespaceSTD;

 

For other types of Vector Data, you need to write the sorting function by yourself and call the Syntax:

Sort (vectemp. Begin (), vectemp. End (), comfun); comfun is a self-defined sorting function. Specifies what rules are "less"

Example:

Define struct

Typedef
StructN_elem

{

LongNID;

DoubleDvalue;

} Nodeelem;

//Compare predicted values

BoolCompprevalue (nodeelem first, nodeelem second)

{

If(First. dvalue <= second. dvalue) // It ranges from large to small. If you want to change from small to large, you can change it to greater than the number.

{

Return
False;

}

Else

{

Return
True;

}

}

//Sort, from large to small

Sort (vecpreresult. Begin (), vecpreresult. End (), compprevalue );

Note: The first and second parameters of the sort function specify the start position (included) and end position (not included) for sorting, that is, [a, B ), the third parameter is a custom comparison function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.