C++ Vectors
![]()
Why we need them:
Vectors allow us to keep track of larger lists of numbers and strings, and allows us to access those data using "index" notation.
A vector is declared using the following format:
vector<type> name; // for size zero
vector<type> name(size); //for a vector of
integer 'size'
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 sorts a user input list of numbers:
// example program using functions and
vectors
// this program orders a user input vector of doubles from small to large
#include <iostream>
#include <vector>
using namespace std;
void vectorSmallToLarge(vector<double> & passedVector);
void switcher(double & a, double & b);
int main ()
{
cout << endl;
cout << "This program takes a user input series of " << endl;
cout << "numbers and orders them from smallest to largest."
<< endl << endl;
cout << "Please input size of list to be input: ";
int sizeV;
cin >> sizeV;
// now declare vector of appropriate size
vector<double> userV(sizeV);
// ask for data and increase size of vector
for( int i=0; i<sizeV; i=i+1)
{ cout << "Please input number " <<
i+1 << ": ";
cin >> userV[i];
}
cout << endl;
// sort the vector using the function
vectorSmallToLarge(userV);
// output the sorted vector
cout << "Your list of numbers, sorted from small to large: "
<< endl;
for( int i=0; i<sizeV; i=i+1)
{
cout << userV[i];
cout << " ";
}
cout << endl; // add one more carriage return to make the
screen look pretty
return 0;
}
// this is the function that sorts the vector
void vectorSmallToLarge(vector<double> & passedVector)
{
bool switched = true;
while(switched)
{
switched = false;
for (int j=0;j<passedVector.size()-1;
j=j+1)
{
if(passedVector[j]>passedVector[j+1])
{switcher(passedVector[j],passedVector[j+1]);
switched = true;
}
}
}
return;
}
// this is the function that switches two values
void switcher(double & a, double & b)
{
double temp = a;
a=b;
b=temp;
return;
}