gpt4 book ai didi

c++ - 寻找给定 vector 的最小值

转载 作者:太空狗 更新时间:2023-10-29 23:42:17 25 4
gpt4 key购买 nike

如何有效地找到给定 vector 集中每一列的最小值?

例如,考虑以下程序:

#include <iostream>
#include <vector>
#include <iterator>
#include <cstdlib>
using namespace std;

typedef vector<double> v_t;

int main(){

v_t v1,v2,v3;

for (int i = 1; i<10; i++){
v1.push_back(rand()%10);
v2.push_back(rand()%10);
v3.push_back(rand()%10);
}

copy(v1.begin(), v1.end(), ostream_iterator<double>(cout, " "));
cout << endl;
copy(v2.begin(), v2.end(), ostream_iterator<double>(cout, " "));
cout << endl;
copy(v3.begin(), v3.end(), ostream_iterator<double>(cout, " "));
cout << endl;
}

让输出为

3 5 6 1 0 6 2 8 2 
6 3 2 2 9 0 6 7 0
7 5 9 7 3 6 1 9 2

在这个程序中,我想找到每列(3 个给定 vector 中)的最小值并将其放入一个 vector 中。在这个程序中,我想定义一个 vector v_t vfinal,它的值是:

3 3 2 1 0 0 1 7 0

有没有有效的方法来做到这一点?我提到高效是因为我的程序可能必须在非常多的 vector 中找到最小值。谢谢。

更新:

我正在尝试使用我在以前的一个程序中使用过的类似的东西

int count = std::inner_product(A, A+5, B, 0, std::plus<int>(), std::less<int>());

这会计算两个数组 A 和 B 之间的最小元素数。如果我可以遍历并使用类似类型的函数来查找最小值,这是否足够有效?我并不是说它能不能做到。这只是一个可以改进的想法,但我不知道如何改进。

最佳答案

为此,您可以使用 std::transform。循环仍然存在,它们只是隐藏在算法中。每个要处理的附加 vector 都是对 std::transform 的调用。

这会在两个线性 channel 中解决您的示例问题。

typedef std::vector<double> v_t;

int main()
{
v_t v1,v2,v3,vfinal(9); // note: vfinal sized to accept results

for (int i = 1; i < 10; ++i) {
v1.push_back(rand() % 10);
v2.push_back(rand() % 10);
v3.push_back(rand() % 10);
}

std::transform(v1.begin(), v1.end(), v2.begin(), vfinal.begin(), std::min<double>);
std::transform(v3.begin(), v3.end(), vfinal.begin(), vfinal.begin(), std::min<double>);
}

注意:这适用于 MSVC++ 2010。我必须为 gcc 4.3 提供一个 min 仿函数。

关于c++ - 寻找给定 vector 的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5047080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com