РУКОВОДСТВО ПО СТАНДАРТНОЙ БИБЛИОТЕКЕ ШАБЛОНОВ (STL)
Шрифт:
cout ‹‹ "At Beginning: " ‹‹ *location ‹‹ endl;
advance(location, 5);
cout ‹‹ "At Beginning + 5: " ‹‹ *location ‹‹ endl;
return 0;
}
replace1.cpp
#include ‹stl.h›
#include ‹iostream.h›
int main {
vector‹int› v1(10);
for (int i = 0; i ‹ v1.size; i++) v1[i] = i % 5;
ostream_iterator‹int› iter(cout, " ");
copy(v1.begin, v1.end, iter);
cout ‹‹ endl;
replace(v1.begin, v1.end, 2, 42);
copy(v1.begin, v1.end, iter);
cout ‹‹ endl;
return 0;
}
alg3.cpp
#include ‹iostream.h›
#include ‹stl.h›
int main {
vector‹int› i;
i.push_back(1);
i.push_back(4);
i.push_back(2);
i.push_back(8);
i.push_back(2);
i.push_back(2);
int n = 0; // Must be initialized, as count increments n.
count(i.begin, i.end, 2, n);
cout ‹‹ "Count of 2s = " ‹‹ n ‹‹ endl;
return 0;
}
func2.cpp
#include ‹iostream.h›
#include ‹stl.h›
bool bigger_than(int x_, int y_) {
return x_ › y_;
}
int main {
vector‹int›v;
v.push_back(4);
v.push_back(1);
v.push_back(5);
sort(v.begin, v.end, bigger_than);
vector‹int›::iterator i;
for (i = v.begin; i != v.end; i++) cout ‹‹ *i ‹‹ endl;
return 0;
}
unegate1.cpp
#include ‹iostream.h›
#include ‹stl.h›
struct odd: public unary_function‹int, bool› {
odd {}
bool operator (int n_) const {return (n_ % 2) - 1;}
};
int array[3] = {1, 2, 3};
int main {
int* p = find_if(array, array + 3, unary_negate‹odd›(odd));
if (p != array + 3)
cout ‹‹ *p ‹‹ endl;
return 0;
}
alg4.cpp
#include ‹iostream.h›
#include ‹stl.h›
int main {
vector‹int› years;
years.push_back(1962);
years.push_back(1992);
years.push_back(2001);
years.push_back(1999);
sort(years.begin, years.end);
vector‹int›::iterator i;
for (i = years.begin; i!= years.end; i++)
cout ‹‹ *i ‹‹ endl;
return 0;
}
countif1.cpp
#include ‹stl.h›
#include ‹iostream.h›
int odd(int a_) {
return a_ % 2;
}
int main {
vector‹int› numbers(100);
for (int i = 0; i ‹ 100; i++) numbers[i] = i % 3;
int elements = 0;
count_if(numbers.begin, numbers.end, odd, elements);
cout ‹‹ "Found " ‹‹ elements ‹‹ " odd elements." ‹‹ endl;
return 0;
}
lwrbnd1.cpp
#include ‹stl.h›
#include ‹iostream.h›
int main {
vector‹int› v1(20);
for (int i = 0; i ‹ v1.size; i++) {
v1[i] = i/4;
cout ‹‹ v1[i] ‹‹ ' ';
}
int* location = lower_bound(v1.begin, v1.end, 3);
cout ‹‹ "\n3 can be inserted at index: " ‹‹ (location - v1.begin) ‹‹ endl;
return 0;
}
lexcmp1.cpp
#include ‹stl.h›
#include ‹iostream.h›
const unsigned size = 6;
char n1[size] = "shoe";
char n2[size] = "shine";
int main {
bool before = lexicographical_compare(n1, n1 + size, n2, n2 + size);
if (before) cout ‹‹ n1 ‹‹ " is before " ‹‹ n2 ‹‹ endl;
else cout ‹‹ n2 ‹‹ " is before " ‹‹ n1 ‹‹ endl;
return 0;
}
copyb.cpp
#include ‹stl.h›
#include ‹iostream.h›
int main {
vector‹int› v1(10);
for (int i = 0; i ‹ v1.size; i++) v1[i] = i;
vector‹int› v2(v1.size);
copy_backward(v1.begin, v1.end, v2.end);
Поделиться с друзьями: