I am trying to add integers to a two dimensional vector.

My problem is on line 26. I know this is how you would add the data to an array, but how do you do this for a vector?

Also, is it true you cannot pass an array to a function as a parameter?

int main()
	const short s = 10;
	const short r = 10000;
	const string fileName = "Lab9.txt";

	vector< vector<short> > matrix;
	//short matrix[s][r];

	// Open the data file
    ifstream fin(fileName.c_str());
    if (!fin.is_open()) 
        cout << endl << "Unable to open input file " << fileName << endl;
        return 1;
    }// End if (!fin.is_open())

	// Fill up matrix
	int temp = 0;
	for(int t = 0; t < s ; t++)
		for(int i = 0; i < r; i++)
				fin >> temp;
		}// End for(int i = 0; i < r; i++)
	}// End for(int t = 0; t < s ; t++)


	cout << matrix[0][9] << endl;

The file compiles when I remove the [t], but I need to keep track of t, because I am trying to create a 10x10000 matrix.


Seems like you should remove the i, not the t. For a 2-D array, I assume you are doing this...

matrix[t][i] = temp;

and you want to convert that code. You can either add an element to a vector or change an element that you already have. In your case, since you are using push_back on a 2-D vector, you'll use ONE, not TWO [] operators, so it's going to be this...


Unlike arrays, you don't need i. You don't need to tell the vector where to put the element. An array doesn't know where the "end" is, but a vector does.

On the other hand, if you know ahead of time what your vector sizes should be, don't use push_back. Instead, set their capacities using "resize" or "reserve" and then set the elements as you would in an array...

matrix[t][i] = temp;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.