我不太擅长使用头文件,但我想使用头文件从文件中读取数据,并在主cpp文件中将数据作为向量返回。
下面是我的readposcar.h文件:
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int add(void) {
double a1x, a1y, a1z, a2x, a2y, a2z, a3x, a3y, a3z; // I want all this stuff in vector form
int i;
double scale;
string line; stringstream dum;
ifstream poscar ("POSCAR");
for (i=1; i<=5; i++) {
getline(poscar,line);
if (i==2) {stringstream dum(line); dum >> scale;}
if (i==3) {stringstream dum(line); dum >> a1x >> a1y >> a1z;}
if (i==4) {stringstream dum(line); dum >> a2x >> a2y >> a2z;}
if (i==5) {stringstream dum(line); dum >> a3x >> a3y >> a3z;}
}
vector<double> myvec(3);
myvec[0] = a1x;
myvec[1] = a1y;
myvec[2] = a1z;
return myvec;
}这是我的.cpp文件:
#include <iostream>
#include <fstream>
#include "readposcar.h"
using namespace std;
int main(void) {
int nbasis = 2;
int nkpts = 10;
vector<double> myvec2(3);
myvec2 = add();
cout << "No. of k-points: " << nkpts << endl;
return 0;
}这显然行不通。有人能告诉我哪里出了问题吗?我需要做些什么才能让它正常工作?只有当我在.h文件中返回myvec2,而不是整个数组时,我才能让它工作。
如果向量不起作用,我不介意将它作为一个数组。是否可以将头文件中的数组初始化为一种全局数组,然后在.cpp文件中简单地调用它?
下面是我得到的错误:
在main.cpp:4:0包含的文件中:
readposcar.h: In function ‘int add()’:
readposcar.h:27:9: error: cannot convert ‘std::vector<double>’ to ‘int’ in return
main.cpp: In function ‘int main()’:
main.cpp:12:15: error: no match for ‘operator=’ in ‘myvec2 = add()’发布于 2013-06-29 20:21:07
您应该将add的返回类型从int更改为vector<double>
发布于 2013-06-29 20:21:00
您返回的类型不正确。尝试:
vector<double> add() {
...
return myvec;
}但是,我个人会在调用者的作用域内传递一个对vector的引用,并返回布尔成功(可选):
bool add(vector<double> &myvec) {
...
return true;
}因为这避免了复制vector,这可能很昂贵,除非C++编译器能够使用RVO来优化复制操作,在这种情况下,您可以使用前面的方法语义。
(感谢@aryjczyk和@AlexB指出最后这一点)。
发布于 2013-06-29 20:23:58
另外,考虑传递一个向量的引用。
因此,您的函数的签名将更改为:
int add( std::vector<double> & values )这样,当从函数返回时,您将避免不必要的复制。
https://stackoverflow.com/questions/17380078
复制相似问题