STL-vector
STL-vector
Provides an alternative to
the built in array.
A vector is self grown.
Use It instead of the built in
array!
Defining a new vector
Syntax: vector<of what>
For example :
vector<int> - vector of integers.
vector<string> - vector of
strings.
vector<int * > - vector of
pointers to integers.
vector<Shape> - vector of Shape
objects. Shape is a user defined
class.
Using Vector
#include <vector>
int ia[N];
for ( int j = 0; j < N; ++j)
ia[j] = ivec[j];
}
Using a vector – STL
style
We define an empty vector
vector<string> svec;
svec.push_back(str);
Size
unsigned int size();
int main()
{
int input;
vector<int> ivec;
/* rest of code */
}
STL - Input
sort(ivec.begin(), ivec.end());
Sort Prototype:
void sort(Iterator first, Iterator
last);
STL - Output
Or (more recommended)
vector<int>::iterator it;
for ( it = ivec.begin(); it != ivec.end(); ++it )
cout << *it << " ";
cout << endl;
STL - Include files
// input
while (cin >> input )
ivec.push_back(input);
// sorting
sort(ivec.begin(), ivec.end());
// output
vector<int>::iterator it;
for ( it = ivec.begin();
it != ivec.end(); ++it ) {
cout << *it << " ";
}
cout << endl;
return 0;
}
Operations on vector
iterator begin();
iterator end();
bool empty();
iterator back();
void push_back(const T& x);
void pop_back(const T& x);
void clear();
….
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
int S=0;
while (!myvector.empty())
{
S += myvector.back();
myvector.pop_back();
}
return 0;
}