首先,为了简单起见,让我们编写一个简单的函数来打印出向量的内容。现在,要查看向量的外观,我们只需调用该函数并查看它的外观即可。
template <typename T>
void printVector(const vector<T> &input){
unsigned sz = input.size();
cout<<"========"<<endl;
for(unsigned i=0; i<sz; i++){
cout<<input[i]<<endl;
}
cout<<"========"<<endl;
}
记住,如果一个函数接受一个泛型类的对象(例如std::vector),你需要指定它是一个模板函数。
现在,回到你的问题。我假设您不想更改 data 本身的值,因为您声明了 data2。
那么您有两个选择(如果我理解您要解决的问题)。
第一种选择是编写一个返回向量的函数。
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
vector<T> doublingFunc(const vector<T> &input){
vector<T> output;
/* it is good practice
to catch the size of the vector
once so that you aren't calling
vector::size() each go through
of the loop, but it is no big deal
*/
unsigned sz = input.size();
for(unsigned i=0; i<sz; i++){
output.push_back(2*input[i]);
}
return output;
}
template <typename T>
void printVector(const vector<T> &input){
unsigned sz = input.size();
cout<<"========"<<endl;
for(unsigned i=0; i<sz; i++){
cout<<input[i]<<endl;
}
cout<<"========"<<endl;
}
int main(){
vector<double> data;
for(int i=1; i<10; i++){
data.push_back((double) i);
//technically, the cast in unnecessary
}
printVector(data);
vector<double> data2 = doublingFunc(data);
printVector(data2);
return 0;
}
第二种选择是编写一个函数,动态分配一个新向量,然后返回一个指向它的指针。
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
vector<T>* doublingFunc(const vector<T> &input){
vector<T>* output = new vector<T>();
/* it is good practice
to catch the size of the vector
once so that you aren't calling
vector::size() each go through
of the loop, but it is no big deal
*/
unsigned sz = input.size();
for(unsigned i=0; i<sz; i++){
output->push_back(2*input[i]);
}
return output;
}
template <typename T>
void printVector(const vector<T> &input){
unsigned sz = input.size();
cout<<"========"<<endl;
for(unsigned i=0; i<sz; i++){
cout<<input[i]<<endl;
}
cout<<"========"<<endl;
}
int main(){
vector<double> data;
for(int i=1; i<10; i++){
data.push_back((double) i);
}
printVector(data);
vector<double>* data2 = doublingFunc(data);
/*this function takes a reference to a vector,
so we need to dereference the pointer
*/
printVector(*data2);
//remember to delete dynamically allocated variables
delete data2;
return 0;
}
当然,如果你只想打印出向量中所有条目的两倍值,你可以使用函数:
template <typename T>
void printDouble(const vector<T> &input){
unsigned sz = input.size();
cout<<"========"<<endl;
for(unsigned i=0; i<sz; i++){
cout<<2 * input[i]<<endl;
}
cout<<"========"<<endl;
}
这对你来说可能是很多新东西,因为你似乎对 c++ 很陌生。我建议阅读this 网站。