【问题标题】:sorting two vectors using c++ with condition使用带有条件的 C++ 对两个向量进行排序
【发布时间】:2016-10-04 06:25:04
【问题描述】:

我有两个向量向量 a 和向量 b,我想用 a[i]/b[i]>a[i+1]/b[b+1] 的条件对它们进行排序。我如何在 C++ 中实现代码?

【问题讨论】:

  • 你能分享你为解决这个问题而制作的程序吗?

标签: c++ c++11


【解决方案1】:

假设你开始

#include <vector>
#include <algorithm>

int main() {
    std::vector<int> a{2, 7, 3};
    std::vector<int> b{4, 2, 1};

创建一个索引向量,inds

    std::vector<std::size_t> inds;
    for(std::size_t i = 0; i < a.size(); ++i)
        inds.push_back(i);

还可以创建一个比较函数来描述您问题中的标准:

    auto cmp = [&](std::size_t lhs, std::size_t rhs) {
        return static_cast<double>(a[lhs]) / b[lhs] > static_cast<double>(a[rhs]) / b[rhs];
    };

并根据它进行排序:

    std::sort(std::begin(inds), std::end(inds), cmp);
}

此时,inds 将根据您的标准进行组织。

最后,使用reorder a vector using a vector of indices 中的答案根据inds 重新排序ab

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多