Wednesday, March 24, 2010

Vector for string

int main() {
vector < string > v;
string name;
cout << "Key in (stop) to end " << endl;
do {
cout << "=> ";
cin >> name;
if (name!="stop")
v.push_back(name);
} while (name!="stop");

cout<< endl;
for (int i=0;i < v.size();i++)
cout << v[i] << " ";
}

Pop_back function

// pop_back - remove an item from the end of the container
int main() {

vector < int > v;
v.push_back(5); v.push_back(1);
cout << "size = " << v.size()<< endl; // return size

v.push_back(3); v.push_back(7);
v.push_back(4);
cout << "size = " << v.size()<< endl;

v.pop_back(); v.pop_back();
cout << "size = " << v.size()<< endl;

for (int i=0;i cout << v[i] << " "; cout << endl;

}

Vector class - print out series of inverse numbers

#include < iostream>
#include < vector>
using namespace std;
int main() {
vector < int> v;
int n;

cout<<"Key in -1 to end the list of numbers"<< endl;
do {
cout << "=> ";
cin >> n;
if (n!=-1) v.push_back(n);
} while (n!=-1);// Enter -1 to exit

for (int i=0; i < v.size() ; i++)
cout << v[v.size()-i-1] << " "; // print out inverse list

}

Vector class

#include < iostream>
#include < vector>
using namespace std;
// push_back(), add an item to the end of the container
int main() {
vector < int > v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);


for (int i=0;i<4;i++)
cout << v[i] << " ";
}