【问题标题】:how to sort a vector without loosing its order c++?如何在不丢失其顺序 C++ 的情况下对向量进行排序?
【发布时间】:2020-11-12 05:01:55
【问题描述】:
int a[10], b[10];
    for (int i = 0; i < 10; i++)
    {
        cin >> a[i];
        b[i] = i;
    }
    sort(b, b + 10, [=](int i, int j) { return a[i] < a[j]; }) return 0;

以上代码将排序后的数组的顺序存储在数组b[10]
如何在 vector&lt;int&gt; 中执行此操作?
不要使用vector&lt;pair&lt;int,int&gt;&gt;回答实现

【问题讨论】:

  • 有什么原因你不能用向量做基本完全相同的事情,在需要的地方替换迭代器?
  • 如果您将int a[10]; 更改为std::vector&lt;int&gt; a(10);,您已有的代码应该可以工作。

标签: c++ sorting stl stdvector


【解决方案1】:
std::sort(b, b + 10, ...);

相当于:

std::sort(std::begin(b), std::end(b), ...);

现在,如果您将 bint b[10]; 更改为 std::vector&lt;int&gt; b(10);,则后一个代码仍然有效并且执行正确的操作。如果您将int a[10]; 更改为std::vector&lt;int&gt; a(10);,则无需进一步更改。

此外,使用[=] 将数组/向量a 复制到lambda 捕获中是没有意义的,请使用[&amp;] 捕获作为参考。

完整代码:

#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> a;
    for(int n = 10, value; n-- && (std::cin >> value);) // Read up to 10 values.
        a.push_back(value);
    // Create index of a and sort it.
    using size_type = decltype(a.size()); // Pedantically, should a have a custom allocator with a custom size_type.
    std::vector<size_type> a_index(a.size());
    std::iota(std::begin(a_index), std::end(a_index), size_type{});
    std::sort(std::begin(a_index), std::end(a_index), [&](size_type i, size_type j) { return a[i] < a[j]; });
}

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2023-03-28
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 2018-05-20
    相关资源
    最近更新 更多