Q: 关于STL Vector作为函数参数使用问题

realda 2013-04-26 11:27:45
最近刚接触STL vector容器,对于容器的使用存在很多问题,现在碰到了一个问题是vector能否作为一个函数的参数呢?

我尝试写了一个code,如下:

#include <cstdlib>
#include <vector>
#include <iostream>

using std::vector;
using std::cout;
using std::endl;
using std::ios;

void calculateAdjClosePrice(double *close, double *open, double *adj_close);

int main(int argc, char** argv) {
vector<double> close;
vector<double> open;
vector<double> adjclose;
close.push_back(2.02);
open.push_back(1.52);
adjclose.push_back(1);

calculateAdjClosePrice(close,open,adjclose);

return 0;
}

void calculateAdjClosePrice(vector<double> close, vector<double> open, vector<double> adj_close){
int size=close.size();
adj_close.clear();
for(int i=0;i<size;i++){
if (close.at(i)>open.at(i))
adj_close.push_back(close.at(i)+0.01*open.at(i));
else
adj_close.push_back(close.at(i)-0.01*open.at(i));
}
vector<double>::iterator p;
for (p=adj_close.begin();p!=adj_close.end();p++)
cout<<*p<<endl;
}


运行后出现报错,如下:
Trial.cpp:20: error: cannot convert `std::vector<double, std::allocator<double> >' to `double*' for argument `1' to `void calculateAdjClosePrice(double*, double*, double*)'

不知道错在哪里,请求高手们指点!
...全文
195 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
starytx 2013-04-26
  • 打赏
  • 举报
回复
提醒lz一下:对于容器能大型数据一般使用const引用作为形参,如果需要改变实参就去掉const直接用引用,以避免不必要的数据拷贝开销
realda 2013-04-26
  • 打赏
  • 举报
回复
。。。没什么。。。我知道那里错了!!!谢谢啦!我结贴了!
ri_aje 2013-04-26
  • 打赏
  • 举报
回复
因为主楼里的两个 calc 函数不是一个东西,第一个只声明了,没有提供定义,但是也没有调用。第二个有声明有定义,不过来得太晚了,所以让你放前面去。
realda 2013-04-26
  • 打赏
  • 举报
回复
果然可以。。。谢谢啊!但是还是有些不明白?按理说,对于一般的函数,可以先定义函数形式,然后在最后具体定义函数内容。但是为什么对于vector,这样定义函数就不行呢?例如:

#include <cstdlib>
#include <cstring>
#include <string>
#include<iostream>

using std::cout;
using std::cerr;
using std::endl;

template <class T>
void strswap(T* a, T* b);

int main(int argc, char** argv) {
    char *A="I am a graduate student";
    char *B="You are a financial man";
    strswap(A,B);
    cout<<"A = "<<A<<endl;
    cout<<"B = "<<B<<endl;
    return 0;
}

template <class T>
void strswap(T* a, T* b){
    if (strlen(a)!=strlen(b))
        cerr<<"Error: The length of the string should be matched."<<endl;
    else{
        int len=strlen(a);
        T *c=new T [len+1];
        for (int i=0;i<len;i++){
            c[i]=a[i];
            a[i]=b[i];
            b[i]=c[i];
        }
        delete []c;
    }
}
我先定义了函数形式:void strswap(T* a, T* b); 最后再定义其具体形式。 这样定义函数在这个例子中是可行的,为什么在vector的例子中就不可行了呢?
mujiok2003 2013-04-26
  • 打赏
  • 举报
回复
把函数定义放在main之前。注意你用了重载。

64,691

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧