C++ Vectors (of Vectors!) Woo hoo! 2-dimensional matrices!
![]()
Why we need them:
2-d vectors allow us to analyze data, keep track of 2-d data sets, and program basic games.
A vector is declared using the following format:
vector<type> name; // for size zero
vector<type> name(size); //for a vector of
integer 'size'
A 2-d vector is declared like this:
vector<vector<int> > table(sizeV, sizeV);
Other useful vector commands:
vectorName.pop_back(); // removes the last
element of the vector
vectorName.size(); // returns the number of
elements of the vector
vectorName.push_back(variable); // adds
variable to the end of the vector, i.e. makes the variable bigger!
vectorname.resize(newsize); //
changes the vector to be of size newsize
vectorname.resize(newsize, element);
// changes the vector to be of size newsize, and fills the new spots with
element
Example program that a 2-d vector, and fills it with zeros and ones:
// example program using vectors of vectors // this program creates a vectors of vectors (a table) // and then fills the table with ones or zeros, // based on a user specified probability
#include <iostream> #include <vector>
using namespace std;
int main ()
{
cout << endl;
cout << "This program creates a vector of vectors (called a table) " << endl;
cout << "and fills each element with either a zero or one, based on" << endl;
cout << "a user-specified probability." << endl << endl;
cout << "Please input size of list to be input: ";
int sizeV;
cin >> sizeV;
cout << endl;
// now declare vector of appropriate size
vector<vector<int> > table(sizeV, sizeV);
// ask for probability of having a one in each element
cout << "Please input the probability of having a one in ";
cout << "each element: ";
double probONE;
cin >> probONE;
cout << endl;
// error checking to weed out those too ignorant to know what a probability is // using a loop that will continue until the user gets it right!
while ( (probONE < 0) or (probONE > 1) )
{ cout << "The probability of something must be between zero and one. Please try again.";
cout << endl << endl;
cout << "Please input the probability of having a one in";
cout << "each element: ";
cin >> probONE;
}
// now fill the table with ones and zeros
// I will use nested whiles because we haven't gotten to "for" loops yet
int i = 0;
int j = 0;
while (i < sizeV)
{
j = 0;
while (j < sizeV)
{
if (probONE > static_cast<double>(rand())/RAND_MAX )
{table [i] [j] = 1;}
else
{table [i] [j] = 0;}
j=j+1;
}
i=i+1;
}
// need to output the table to the screen
i = 0; // remember not to redeclare these counters, just zero them out again
j = 0;
while (i < sizeV)
{
j = 0;
while (j < sizeV)
{
cout << table [i] [j] << " ";
j=j+1;
}
cout << endl;
i=i+1;
}
cout << endl; // add one more carriage return to make the screen look pretty
return 0;
}