【发布时间】:2011-02-18 22:03:48
【问题描述】:
如何有效地找到给定向量集中每一列的最小值?
例如,考虑以下程序:
#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 个给定向量)的最小值并将其放入向量中。在这个程序中,我想定义一个向量v_t vfinal,它将具有以下值:
3 3 2 1 0 0 1 7 0
有没有一种有效的方法来做到这一点?我提到高效是因为我的程序可能必须在大量向量中找到最小值。谢谢你。
更新:
我正在尝试使用我在以前的一个程序中使用过的类似的东西
int count = std::inner_product(A, A+5, B, 0, std::plus<int>(), std::less<int>());
这会计算两个数组 A 和 B 之间的最小元素的数量。如果我可以循环并使用类似的函数来查找最小值,这不是足够有效吗?我并不是说它可以完成或不能完成。这只是一个可以改进的想法,但我不知道如何。
【问题讨论】:
-
如果您关心的是效率,您应该考虑按列而不是按行存储表格。