You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对任意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:

  1. Include the <cmath> header for the abs() function (use fabs() for floating-point types like double).
  2. Use std::sort with 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::sort with std::stable_sort. For example, if your vector had {3, -3}, stable_sort would keep them in their original order, while sort might swap them.
  • For floating-point vectors (e.g., std::vector<double>), use std::fabs() instead of std::abs() to handle non-integer values correctly.

内容的提问来源于stack exchange,提问作者ashok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:57:43