How do I set up a function that returns a pointer to a vector in C++?
I need help figuring out bits of code. I need a function that loads up a vector with given strings and returns a pointer. I plan to use it to generate multiple vectors and then use the pointer to display them.
I am not sure how to set up both the return of the pointer by the function and the la开发者_如何学运维ter display of the vectors. Please make suggestions only on lines that contain //HELP NEEDED HERE
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int pointerReturner (string str1, string str2) //HELP NEEDED HERE
{
vector<string> vList;
vList.push_back(str1);
vList.push_back(str2);
return vList; //HELP NEEDED HERE
}
int main(int argc, char* argv[]) {
vector<string> vMakeList1;
vMakeList1 =pointerReturner("Honda","Toyota");//HELP NEEDED HERE
for (vector<string>::iterator n=vMakeList1.begin(); n!=vMakeList1.end();++n)
{
cout<<*n<<endl;
}
vector<string> vMakeList2;
vMakeList2=pointerReturner("Chrysler","Ford");//HELP NEEDED HERE
for (vector<string>::iterator n=vMakeList2.begin(); n!=vMakeList2.end();++n)
{
cout<<*n<<endl;
}
cin.get();
return 0;
}
You have to allocate the vector dynamically using the new operator. Otherwise the vector is just an automatic variable that is destroyed after the function pointerReturner ends. You also have to change the return type of this function from int to a pointer to a vector (vector*). But if you allocate an object dynamically you have to destroy it explicitly using the delete operator, otherwise the allocated memory will never be released which would result in a memory leak.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string>* pointerReturner (string str1, string str2)
{
vector<string> *vList = new vector<string>();
vList->push_back(str1);
vList->push_back(str2);
return vList;
}
int main(int argc, char* argv[]) {
vector<string> *vMakeList1;
vMakeList1 = pointerReturner("Honda","Toyota");
for (vector<string>::iterator n=vMakeList1->begin(); n!=vMakeList1->end();++n)
{
cout<<*n<<endl;
}
delete vMakeList1;
vector<string> *vMakeList2;
vMakeList2=pointerReturner("Chrysler","Ford");
for (vector<string>::iterator n=vMakeList2->begin(); n!=vMakeList2->end();++n)
{
cout<<*n<<endl;
}
delete vMakeList2;
cin.get();
return 0;
}
精彩评论