can`t store different values into vector by user input

Hi guys, i`m facing a problem. I can`t seem to store multiple values into my vector when a user keys in an input.

Lets say a user inputs 1,2 as the first set and later keys in 3,4.
My vector gets overridden by 3 and 4.

i`m trying to pass these values into a function to store them into a vector and use them in the function Hope you guys can enlighten me on this. Thanks in advance

below is my code snippet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int reconstructSecret(int x, int y)
{
    int getX,getY;
    getX=x;
    getY=y;

    vector<int> myXCordVec;
    vector<int> myYCordVec;
    myXCordVec.push_back(getX);
    myYCordVec.push_back(getY);

    for(int i=0;i<myXCordVec.size();i++)
    {
        cout<<myXCordVec[i]<<endl;
    }
}


main method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 cout<<"Reconstruction of Secret"<<endl;
    cout<<"please key in the number of shares to regenerate the secret";
    cin>>constructSecret;



    for(int i=0;i<constructSecret;i++)
    {
        cout<<"please key in the "<<i<< "share of x value:";
        cin>>x;
        cout<<"please key in the "<<i<< "share of y value:";
        cin>>y;
        reconstructSecret(x,y);

    }
The vectors that you create inside reconstructSecret are local to that function. They will be destroyed when the function ends and the next time the function is called you'll get two different vectors.
i see, so is there any way that i can store the data into a vector in the main method and pass the data inside it to the function?
If you create the vectors in the main function and pass the vectors by reference to the function. That will allow you to use and modify the vectors from within the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int reconstructSecret(int x, int y, vector<int>& myXCordVec, vector<int>& myYCordVec)
{
	int getX,getY;
	getX=x;
	getY=y;
	
	myXCordVec.push_back(getX);
	myYCordVec.push_back(getY);
	
	for(int i=0;i<myXCordVec.size();i++)
	{
		cout<<myXCordVec[i]<<endl;
	}
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	cout<<"Reconstruction of Secret"<<endl;
	cout<<"please key in the number of shares to regenerate the secret";
	cin>>constructSecret;

	vector<int> myXCordVec;
	vector<int> myYCordVec;

	for(int i=0;i<constructSecret;i++)
	{
		cout<<"please key in the "<<i<< "share of x value:";
		cin>>x;
		cout<<"please key in the "<<i<< "share of y value:";
		cin>>y;
		reconstructSecret(x,y, myXCordVec, myYCordVec);
	}
Last edited on
thanks man! correct me if i`m wrong, the same theory applies for arrays as well?
Yes but note that if you pass an array to a function
1
2
int arr[10];
foo(arr);
with the parameter type int*
1
2
3
int foo(int arr[]);
// or
int foo(int* arr);
you are actually passing a pointer to the first element in the array so you don't need to use references here to be able to modify the array elements from within the function.
ok noted on that point! thanks for your help! =)
Topic archived. No new replies allowed.