我试图将一个数组的列作为向量参数传递,但我不知道该怎么做。我正在使用" vector"图书馆。我将发布一个例子来澄清我想要的东西:
#include <iostream>
#include <vector>
using namespace std;
//function for get the sum of all the elements of a vector H
double suma(vector<double> H) {
double Sum = 0.0;
for (int i = 0; i < H.size(); i++) {
Sum += H[i];
}
return Sum;
}
int main() {
vector<vector<double> > phi;
phi.resize(10, vector<double> (2,1.0));
cout << suma(phi[][1]) << endl;
}
它不起作用:(任何人都可以帮助我吗?
提前致谢
答案 0 :(得分:0)
我认为你可以用这种方式编写你的程序
#include <iostream>
#include <vector>
using namespace std;
double suma(vector<vector<double> >& H) {
double Sum = 0.0;
for (size_t i = 0; i < H.size(); ++i) {
// probably you need to write one more inner loop to do
// something with each vector.This is not very clear with your question
}
return Sum;
}
int main() {
vector<vector<double> > phi(10,vector<double> (2,1.0));
cout << suma(phi) << endl;
}
答案 1 :(得分:0)
如果要计算第一列的总和,可以这样做:
#include <iostream>
#include <vector>
using namespace std;
//function for get the sum of all the elements of a vector H
double suma(vector<double> H) {
double Sum = 0.0;
for (int i = 0; i < H.size(); i++) {
Sum += H[i];
}
return Sum;
}
int main() {
vector<vector<double> > phi;
phi.resize(10, vector<double> (2,1.0));
//if by 0th column you mean 0th vector do this:
cout << suma(phi[0]) << endl;
//if by 0th column you mean every 0th element of each vector do this:
vector<double> temp;
for(int i=0; i<phi.size(); i++)
{
temp.push_back(phi[i][0]);
}
cout << suma(temp) << endl;
}