const unsigned nameSize = sizeof(names) / sizeof(names[0]);
vector‹char*› v1(nameSize);
for (int i = 0; i ‹ v1.size(); i++) v1[i] = names[i];
ostream_iterator‹char*› iter(cout, ' ');
copy(v1.begin(), v1.end(), iter);
cout ‹‹ endl;
vector‹char*› result(5);
partial_sort_copy(v1.begin(), v1.end(), result.begin(), result.end(), str_compare);
copy(v1.begin(), v1.end(), iter);
cout ‹‹ endl;
return 0;
}
vec6.cpp
#include ‹iostream.h›
#include ‹stl.h›
int array[] = {1, 4, 9, 16, 25, 36};
int main() {
vector‹int› v(array, array + 6);
for (int i = 0; i ‹ v.size(); i++) cout ‹‹ 'v[' ‹‹ i ‹‹ '] = ' ‹‹ v[i] ‹‹ endl;
cout ‹‹ endl;
v.erase(v.begin()); // Erase first element.
for (i = 0; i ‹ v.size(); i++) cout ‹‹ 'v[' ‹‹ i ‹‹ '] = ' ‹‹ v[i] ‹‹ endl;
cout ‹‹ endl;
v.erase(v.end() - 1); // Erase last element.
for (i = 0; i ‹ v.size(); i++) cout ‹‹ 'v[' ‹‹ i ‹‹ '] = ' ‹‹ v[i] ‹‹ endl;
cout ‹‹ endl;
v.erase(v.begin() + 1, v.end() - 1); // Erase all but first and last.
for (i = 0; i ‹ v.size(); i++)
cout ‹‹ 'v[' ‹‹ i ‹‹ '] = ' ‹‹ v[i] ‹‹ endl;
cout ‹‹ endl;
v.erase(); // Erase all.
return 0;
}
inrprod2.cpp
#include ‹stl.h›
#include ‹iostream.h›
#include ‹string.h›
int add(int a_, int b_) {
return a_ + b_;
}
int mult(int a_, int b_) {
return a_ * b_;
}
int main() {
vector‹int› v1(3);
vector‹int› v2(v1.size());
for (int i = 0; i ‹ v1.size(); i++) {
v1[i] = i + 1;
v2[i] = v1.size() - i;
}
ostream_iterator‹int› iter(cout, ' ');
cout ‹‹ 'Inner product(product of sums):
';
copy(v1.begin(), v1.end(), iter);
cout ‹‹ '
';
copy(v2.begin(), v2.end(), iter);
int result = inner_product(v1.begin(), v1.end(), v2.begin(), 1, mult, add);
cout ‹‹ '
is: ' ‹‹ result ‹‹ endl;
return 0;
}
mmap1.cpp
#include ‹iostream.h›
#include ‹stl.h›
int main() {
typedef multimap‹char, int, less‹char› › mmap;
mmap m;
cout ‹‹ 'count('X') = ' ‹‹ m.count('X') ‹‹ endl;
m.insert(pair‹const char, int›('X', 10)); // Standard way.
cout ‹‹ 'count('X') = ' ‹‹ m.count('X') ‹‹ endl;
m.insert('X', 20); // Non-standard, but very convenient!
cout ‹‹ 'count('X') = ' ‹‹ m.count('X') ‹‹ endl;
m.insert('Y', 32);
mmap::iterator i = m.find('X'); // Find first match.
while (i != m.end()) { // Loop until end is reached.
cout ‹‹ (*i).first ‹‹ ' -› ' ‹‹ (*i).second ‹‹ endl;
i++;
}
int count = m.erase('X');
cout ‹‹ 'Erased ' ‹‹ count ‹‹ ' items' ‹‹ endl;
return 0;
}