Jump to content

Help! Passing a Vector of Structs to a function, and using the modified vector...

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Fidelius

Fidelius

    Newbie

  • Members
  • Pip
  • 1 posts
I am trying to figure out how to pass a vector of structs into a function, and modify the vector's contents, and then continue using the modified vector in the main... this should be relatively easy to master, but I do have trouble getting my head around pointers, and I'm pretty sure that they're required in this case...
Here's some test code to show how I would do it... yet there's something wrong.


#include <vector>

#include <iostream>


using namespace std;


void function (vector<int> *Test){

	Test->push_back(2);

}




int main(void){

	vector<int> test;


	int *testPointer;

	testPointer = &test;


	test.push_back(1);

	

	function(testPointer);


	test.push_back(3);


	for (int i=0; i<test.size(); i++){

		cout << "test[" << i << "] = " << test[i] << "\n";

	}

	return 0;

}


Target output:


test[0] = 1

test[1] = 2

test[2] = 3

What modifications would be made to the code, in order to get this desired output? At the moment it's not even compiling:

Visual C++ 2008 Express Edition said:

testPointer = &test;
- cannot convert from 'std::vector<_Ty> *' to 'int *'


#2
marwex89

marwex89

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 10,720 posts
testPointer shouldn't be a pointer to int.

Posted via CodeCall Mobile

#3
SolidState

SolidState

    Learning Programmer

  • Members
  • PipPipPip
  • 38 posts
Yes as marwex89 has said your int pointer is wrong, since your function takes a vector pointer as its parameter.