#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;


vector<string> function1(vector<string>v)
{
	for(int i=0;i<4;i++)
	{cin>>v[i];}
return v;
}

int main ()
{vector<string>v;
vector<string>guess;
vector<string>guess=function1(vector<string>v);
cout<<"size:"<<guess.size()<<endl;
cout<<"contents:";
for (int i=0; i<guess.size(); i++)
{cout<<guess[i]<<"";}
cout<<endl;
return 0;
}

i need to build vector<string>guess(4) in function function1 and input it to the main. can anyone point my mistake and correct it. i just have no idea..
thanx in advance
fyi=im just a newbie for c++

There are lots of ways to fix up your code, depending on if you want to pass by reference or just return a vector and copy it.

This is creating a vector in function1() and returning it.

#include <iostream>
#include <vector>
#include <string>

using namespace std;


vector<string> function1()
{
	vector<string> v(4);
	for( unsigned int i = 0; i < v.size(); i++ )
		cin >> v[i];
	return v;
}

int main ()
{
	vector<string> guess(4);
	guess = function1();
	cout << "size:" << guess.size() << endl;
	cout << "contents:";

	for( unsigned int i = 0; i < guess.size(); i++ )
		cout << guess[i] << "";
	cout << endl;
	return 0;
}

This is using pass by reference to populate the vector guess.

#include <iostream>
#include <vector>
#include <string>

using namespace std;


void function1(vector<string> &v)
{
	for( unsigned int i = 0; i < v.size(); i++ )
		cin >> v[i];
}

int main ()
{
	vector<string> guess(4);
	function1(guess);
	cout << "size:" << guess.size() << endl;
	cout << "contents:";

	for( unsigned int i = 0; i < guess.size(); i++ )
		cout << guess[i] << "";
	cout << endl;
	return 0;
}

They both give the same result but as a beginner I would suggest sticking with option #1.

As for your code the main issues were that you were redefining a variable on lines 20 and 21, and you were redefining vector v when passing it into function1().

Compare your code to my first example and you will see the corrections.

This article has been dead for over six months. Start a new discussion instead.