如何对任意vector按值排序?以及如何在C++中按绝对值对vector排序?
Hey there! Let's tackle these two C++ vector sorting questions clearly and practically.
1. Sorting a vector by its values (default ordering)
In C++, the standard library gives us the std::sort function (from the <algorithm> header) which makes this straightforward. By default, it sorts elements in ascending order using the < operator for the element type.
Example code:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> vec = {5, 2, 9, 1, 5, 6}; // Sort in ascending order (default) std::sort(vec.begin(), vec.end()); // Print the result for (int num : vec) { std::cout << num << " "; } // Output: 1 2 5 5 6 9 return 0; }
If you need descending order, you can pass the std::greater<T> comparator (include <functional> for this, though some compilers might include it implicitly with <algorithm>):
std::sort(vec.begin(), vec.end(), std::greater<int>()); // Output: 9 6 5 5 2 1
Alternatively, you can use a custom lambda for more control, but the default or std::greater is usually sufficient for basic value sorting.
2. Sorting a vector by absolute value
To sort elements based on their absolute magnitude (like your example where {-10, 12, -20, -8, 15} becomes {-8, -10, 12, 15, -20}), we need to provide a custom comparator that compares the absolute values of the elements.
Step-by-step solution:
- Include the
<cmath>header for theabs()function (usefabs()for floating-point types likedouble). - Use
std::sortwith a lambda expression as the comparator, which returns whether the absolute value of the first element is less than that of the second.
Example code matching your expected output:
#include <iostream> #include <vector> #include <algorithm> #include <cmath> int main() { std::vector<int> nums = {-10, 12, -20, -8, 15}; // Sort by absolute value in ascending order std::sort(nums.begin(), nums.end(), [](int a, int b) { return std::abs(a) < std::abs(b); }); // Print the result for (int num : nums) { std::cout << num << " "; } // Output: -8 -10 12 15 -20 (matches your expectation) return 0; }
Notes:
- If you need a stable sort (preserving the relative order of elements with the same absolute value), replace
std::sortwithstd::stable_sort. For example, if your vector had{3, -3},stable_sortwould keep them in their original order, whilesortmight swap them. - For floating-point vectors (e.g.,
std::vector<double>), usestd::fabs()instead ofstd::abs()to handle non-integer values correctly.
内容的提问来源于stack exchange,提问作者ashok

