stl algorithm example

it2026-01-19  11

#include <vector> #include <algorithm> #include <iostream> bool divby5(int x) { return x % 5 ? 0 : 1; } int square(const int x) { return x*x; } void find_sample() { int num_find = 6; std::vector<int> v1; for (int i=0; i<10; i++) { v1.push_back(2*i); } std::vector<int>::iterator result; result = find(v1.begin(), v1.end(), num_find); if (result == v1.end()) { std::cout << "not found: " << num_find << std::endl; } else { std::cout << "found: " << result-v1.begin() << std::endl; } } void find_if_sample() { std::vector<int> v(20); for (int i=0; i<v.size(); i++) { v[i] = (i+1) * (i+3); std::cout << v[i] << std::endl; } int count_find = 15; std::vector<int>::iterator ilocation; ilocation = find_if(v.begin(), v.end(), divby5); const int num_find = count(v.begin(), v.end(), count_find); if (ilocation != v.end()) { std::cout << "find num less than 5: " << *ilocation << " at: " << ilocation-v.begin() << std::endl; std::cout << "find count equal 15: " << num_find << std::endl; std::cout << "less than 5 num is: " << count_if(v.begin(), v.end(), divby5) << std::endl; } } void transform_sample() { std::vector<int> v1(20), v2(20); for (int i=0; i<v1.size(); i++) { v1[i] = (i+1) * (i+3); } generate_n(v1.begin(), 15, rand); transform(v1.begin(), v1.end(), v2.begin(), square); unique(v1.begin(), v1.end()); sort(v1.begin(), v1.end()); std::vector<int>::iterator ti; for (ti=v2.begin(); ti!=v2.end(); ti++) { std::cout << *ti << std::endl; } } void sort_heap_sample() { std::vector<int> v1(20), v2(20); for (int i=v1.size(); i>0; i--) { v1[i] = (i+1) * (i+3); } make_heap(v1.begin(), v1.end()); sort_heap(v1.begin(), v1.end()); for (int i=0; i<v1.size(); i++) { std::cout << v1[i] << std::endl; } } int main(int argc, char** argv) { find_sample(); find_if_sample(); transform_sample(); sort_heap_sample(); return 0; }

转载于:https://www.cnblogs.com/octave/p/4428772.html

最新回复(0)