Reputation: 31
I have a problem to get a return value of vector* value. I expect the return of value vector* have a components with size 1000 still after the get_vectorD exits. Let me know what the problem is in the following my code.
#include <iostream>
#include <vector>
using namespace std;
void get_vectorD(vector<int>* D)
{
vector<int>* d_vec = new vector<int>();
for (int i = 0; i < 1000; i++) { d_vec->push_back(i); }
D = d_vec;
}
void main()
{
vector<int>* D = new vector<int>();
get_vectorD(D);
cout << D->at(0) << endl;
}
Upvotes: 2
Views: 150
Reputation: 483
The problem is that you are passing the pointer by value. Pass it by a reference and it will work
void get_vectorD(vector<int>*& D)
{
vector<int>* d_vec = new vector<int>;
for (int i = 0; i < 1000; i++) { d_vec->push_back(i); }
D = d_vec;
}
and you can make use of function return value:
vector<int>* get_vectorD()
{
vector<int>* d_vec = new vector<int>;
for (int i = 0; i < 1000; i++) { d_vec->push_back(i); }
return d_vec;
}
or use pointer of pointer
#include <iostream>
#include <vector>
using namespace std;
void get_vectorD(vector<int>** D)
{
vector<int>* d_vec = new vector<int>;
for (int i = 0; i < 1000; i++) { d_vec->push_back(i); }
*D = d_vec;
}
int main()
{
vector<int>* D;
get_vectorD(&D);
cout << D->at(0) << endl;
delete D;
return 0;
}
Upvotes: 3
Reputation: 12293
Following would work:
#include <iostream>
#include <vector>
using namespace std;
void get_vectorD(vector<int>*& D)
{
D = new vector<int>();
for (int i = 0; i < 1000; i++) { D->push_back(i); }
}
int main()
{
vector<int>* D;
get_vectorD(D);
cout << D->at(0) << endl;
}
Since you are passing the std::vector
's pointer by value, anything you do in the get_vectorD
function won't have any effect on vector<int>* D
. That's why you need to pass a reference to the pointer.
Also, there is no need to have a temporary d_vec
variable in your get_vectorD
function.
Better way
Furthermore, it would have the same effect and would be much less error prone not using the pointer at all like:
#include <iostream>
#include <vector>
void get_vectorD(std::vector<int>& D) {
for (int i = 0; i < 1000; i++) {
D.push_back(i);
}
}
int main() {
std::vector<int> D;
get_vectorD(D);
std::cout << D.at(0) << std::endl;
}
Much better way to fill up the std::vector
Don't forget that you can fill up the std::vector
by using std::iota
like:
std::vector<int> D(1000);
std::iota(D.begin(), D.end(), 0);
Upvotes: 0