Manipulating a char vector from another function

I have a 9-element char vector that gets initialized to spaces when the program runs. During the course of the program, I want to input a number and have it change that number element in the array to something else ('X' in my case). Thing is, I input the number in a different function and I can't figure out how to transfer the change between the two functions.

I'm pretty sure I need to send both an int (for the vector element number) and a char (for the actual change in value), but nothing I've tried has worked.

I might not even be making any sense, I've been working on this for hours now and my mind is starting to melt. If I can clear any confusion, I'd be glad to help.

Here's the code:

1
2
3
//declarations
char charLib(int num, char SXO = ' ');
char checkValidH(int spot);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//vector that needs manipulation
char charLib(int num, char SXO)
{
	vector<char> charLib;
	charLib.push_back(SXO);//0
	charLib.push_back(SXO);//1
	charLib.push_back(SXO);//2
	charLib.push_back(SXO);//3
	charLib.push_back(SXO);//4
	charLib.push_back(SXO);//5
	charLib.push_back(SXO);//6
	charLib.push_back(SXO);//7
	charLib.push_back(SXO);//8

	return charLib[num];
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//one of the functions that'll manipulate it.
char checkValidH(int choice)
{
	if(choice >= 0 && choice <= 8)
	{
	                if(charLib(choice) != 'X' || charLib(choice) != 'O')
		{
			charLib(choice, 'X');
			aiTurn();
			return 0;
		}
		else
		{
			cout << "That spot's already taken, try again.";
			humanTurn();
		}
	}
	else
	{
		cout << "Invalid input.";
		humanTurn();
	}
}

1
2
3
4
5
6
7
8
9
10
11
//human's turn to act, might not be important
int humanTurn()
{
	int choice;

	gameBoard();
	cout << "\nChoose where to put your X: ";
	cin >> choice;
	checkValidH(choice);
	return 0;
}
You can just pass the vector around:
1
2
3
4
5
6
7
void this_function_takes_and_changes_a_vector(vector<char> vec&)
{
  if(vec.length()>=1)
  {
     vec[0]='a';
  }
}
Last edited on
Won't that just make a copy of the vector and not affect the original? I have to call all of the elements of the vector to my gameBoard() function, so I think I need the original to be changed.
Notice the ampersand after the parameter name. That means the parameter is a reference, so no copy is made and all changes occur on the actual object.
I did not see that, and I feel stupid for it. So, would I edit my current charLib() function, or create a whole new one with what you posted? I really appreciate the help, by the way. :)
Well, that depends on what you're actually trying to do with your function. I personally didn't see what you were actually trying to achieve with it.
Topic archived. No new replies allowed.