Vector series in practice c ++-sort the vector using the sort algorithm (sort the vector (string) and use stable sorting std: stable_sort ())
After writing a lot of vector operations, we encountered the Sorting Problem of the vector in our work. Here we will discuss it.
Use the sort algorithm directly:
template
void sort (RandomAccessIterator first, RandomAccessIterator last);template
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
Sorts the elements in the range [first, last) into ascending order.
The elements are compared using operator <for the first version, and comp for the second.
Equivalent elements are not guaranteed to keep their original relative order (see stable_sort ).
That is, the unstable sorting.
Directly run the Code:
# Include
// Std: cout # include // std: sort # include
// Std: vector # include
Bool myfunction (int I, int j) {return (I
Myvector (myints, myints + 8); // 32 71 12 45 26 80 53 33 // using default comparison (operator <) std: sort (myvector. begin (), myvector. begin () + 4); // (12 32 45 71) 26 80 53 33 // using function as comp std: sort (myvector. begin () + 4, myvector. end (), myfunction); // 12 32 45 71 (26 33 53 80) // using object as comp std: sort (myvector. begin (), myvector. end (), myobject); // (12 26 32 33 45 53 71 80) // print out content: std: cout <"myvector contains :"; for (std: vector
: Iterator it = myvector. begin (); it! = Myvector. end (); ++ it) std: cout <''<* it; std: cout <'\ n'; // Sorting the string vector std:: vector
StringVec = {"John", "Bob", "Joe", "Zack", "Randy"}; sort (stringVec. begin (), stringVec. end (); for (std: string & s: stringVec) std: cout <s <"; return 0 ;}// output: myvector contains: 12 26 32 33 45 53 71 80Bob Joe John Randy Zack
In this case, std: stable_sort () can be used to achieve stable sorting:
Sorts the elements in the range [first, last) into ascending order, like sort, but stable_sort preserves the relative order of the elements with equivalent values.
# Include
// Std: cout # include // std: stable_sort # include
// Std: vectorbool compare_as_ints (double I, double j) {return (int (I)
Myvector; myvector. assign (mydoubles, mydoubles + 8); std: cout <"using default comparison:"; std: stable_sort (myvector. begin (), myvector. end (); for (std: vector
: Iterator it = myvector. begin (); it! = Myvector. end (); ++ it) std: cout <''<* it; std: cout <'\ n'; myvector. assign (mydoubles, mydoubles + 8); std: cout <"using 'compare _ as_ints ':"; std: stable_sort (myvector. begin (), myvector. end (), compare_as_ints); for (std: vector
: Iterator it = myvector. begin (); it! = Myvector. end (); ++ it) std: cout <''<* it; std: cout <'\ n'; return 0 ;}// output: using default comparison: 1.32 1.41 1.62 1.73 2.58 2.72 3.14 4.67 1.41 using 'compare _ as_ints ': 1.73 1.32 1.62 2.72 2.58 3.14 4.67