C++算法接口使用参考
C++算法接口参考
算法参考:【algorithm】
编译:g++ -std=c++11 xxx_algorithm.cpp
运行:./a.out
1.保持原序列运算
all_of
template <class InputIterator, class UnaryPredicate> bool all_of(InputIterator first, InputIterator last, UnaryPredicate pred) { while (first != last) { if (!pred(*first)) { return false; } ++first; } return true; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::all_of #include <array> // std::array int main() { std::array<int, 8> foo = {3,5,7,9,11,13,15,17}; if (std::all_of(foo.begin(), foo.end(), [](int i){return i%2;})) { std::cout << "All the elements are odd numbers.\n"; } return 0; } //-----Output----- //All the elements are odd numbers.
any_of
template<class InputIterator, class UnaryPredicate> bool any_of(InputIterator first, InputIterator last, UnaryPredicate pred) { while (first != last) { if (pred(*first)) { return true; } ++first; } return false; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::any_of #include <array> // std::array int main() { std::array<int ,7> foo = {5,3,1,0,-1,-3,-5}; if (std::any_of(foo.begin(), foo.end(), [](int i){return i<0;})) { std::cout << "There are negative elements in the range.\n"; } return 0; } //-----Output----- //There are negative elements in the range.
none_of
template<class InputIterator, class UnaryPredicate> bool none_of(InputIterator first, InputIterator last, UnaryPredicate pred) { while (first != last) { if (pred(*first)) { return false; } ++first; } return true; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::none_of #include <array> // std::array int main() { std::array<int, 8> foo = {1,2,3,4,5,6,7,8}; if ( std::none_of(foo.begin(), foo.end(), [](int i){return i<0;}) ) { std::cout << "There are no negative elements in the range.\n"; } return 0; } //-----Output----- //There are no negative elements in the range.
for_each
template<class InputIterator, class Function> Function forEach(InputIterator first, InputIterator last, Function fn) { while (first != last) { fn(*first); ++first; } //return move(fn); return fn; // or, since c++11: return move(fn); } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::for_each #include <vector> // std::vector void myfunction(int i) { std::cout << ' ' << i; } struct myclass { void operator() (int i) {std::cout << ' ' << i;} }myobject; int main() { std::vector<int> myvector; myvector.push_back(10); myvector.push_back(20); myvector.push_back(30); std::cout << "myvector contains:"; forEach (myvector.begin(), myvector.end(), myfunction); std::cout << '\n'; // or: std::cout << "myvector contains:"; forEach(myvector.begin(), myvector.end(), myobject); std::cout << '\n'; return 0; } //-----Output----- //myvector: 10 20 30 //myvector: 10 20 30
find
template<class InputIterator, class T> InputIterator Find(InputIterator first, InputIterator last, const T& val) { while (first != last) { if (*first == val) { return first; } ++first; } return last; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::find #include <vector> // std::vector int main() { // using std::find with array and pointer: int myints[] = {10, 20, 30, 40}; int *p; //p = std::find(myints, myints+4, 30); p = Find(myints, myints+4, 30); if (p != myints+4) { std::cout << "Element found in myints:" << *p << '\n'; } else { std::cout << "Element not found in myints.\n"; } // using std::find with vector and iterator: std::vector<int> myvector(myints, myints+4); std::vector<int>::iterator it; //it = find(myvector.begin(), myvector.end(), 30); it = Find(myvector.begin(), myvector.end(), 30); if (it != myvector.end()) { std::cout << "Element found in myvector:" << *it << '\n'; } else { std::cout << "Element not found in myvector.\n"; } return 0; } //-----Output----- //Element found in myints:30 //Element found in myvector:30
find_if
template<class InputIterator, class UnaryPredicate> InputIterator find_if(InputIterator first, InputIterator last, UnaryPredicate pred) { while (first != last) { if (pred(*first)) { return first; } ++first; } return last; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::find_if #include <vector> // std::vector bool IsOdd(int i) { return ((i%2)==1); } int main () { std::vector<int> myvector; myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); std::vector<int>::iterator it = std::find_if(myvector.begin(), myvector.end(), IsOdd); std::cout << "The first odd value is:" << *it << '\n'; return 0; } //-----Output----- //The first odd value is:25
find_if_not
template<class InputIterator, class UnaryPredicate> InputIterator find_if_not(InputIterator first, InputIterator last, UnaryPredicate pred) { while (first != last) { if (!pred(*first)) { return first; } } return last; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::find_if_not #include <array> // std::array int main() { std::array<int, 5> foo = {1,2,3,4,5}; std::array<int, 5>::iterator it = std::find_if_not(foo.begin(), foo.end(), [](int i){return i%2;}); std::cout << "The first even value is:" << *it << '\n'; return 0; } //-----Output----- //The first even value is:2
find_end
template <class ForwardIterator1, class ForwardIterator2> ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator2 last1, ForwardIterator2 first2, ForwardIterator2 last2) { if (first2 == last2) { return last1; } ForwardIterator1 ret = last1; while (first1 != last1) { ForwardIterator1 it1 = first1; ForwardIterator2 it2 = first2; while (*it1 == *it2) { ++it1; ++it2; if (it2 == last2) { ret = first1; break; } if (it1 == last1) { return ret; } } ++first1; } return ret; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::find_end #include <vector> // std::vector bool myfunction(int i, int j) { return (i==j); } int main() { int myints[] = {1,2,3,4,5,1,2,3,4,5}; std::vector<int> haystack(myints, myints+10); int needle1[] = {1,2,3}; // using default comparison: std::vector<int>::iterator it; it = std::find_end(haystack.begin(), haystack.end(), needle1, needle1+3); if (it != haystack.end()) { std::cout << "needle1 last found at position:" << (it-haystack.begin()) << '\n'; } int needle2[] = {4,5,1}; // using predicate comparison: it = std::find_end(haystack.begin(), haystack.end(), needle2, needle2+3, myfunction); if (it != haystack.end()) { std::cout << "needle2 last found at position:" << (it-haystack.begin()) << '\n'; } return 0; } //-----Output----- //needle1 found at position:5 //needle2 found at position:3
find_first_of
template<class InputIterator, class ForwardIterator> InputIterator findFirstOf(InputIterator first1, InputIterator last1, ForwardIterator first2, ForwardIterator last2) { while (first1 != last1) { for (ForwardIterator it=first2; it!=last2; ++it) { if (*it == *first1) { return first1; } ++first1; } } return last1; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::find_first_of #include <vector> // std::vector #include <cctype> // std::tolower bool comp_case_insensitive(char c1, char c2) { return (std::tolower(c1) == std::tolower(c2)); } int main() { int mychars[] = {'a', 'b', 'c', 'A', 'B', 'C'}; std::vector<char> haystack(mychars, mychars+6); std::vector<char>::iterator it; int needle[] = {'A', 'B', 'C'}; // using default comparison: it = findFirstOf(haystack.begin(), haystack.end(), needle, needle+3); if (it != haystack.end()) { std::cout << "The first match is:" << *it << '\n'; } // using predicate comparison: //it = findFirstOf(haystack.begin(), haystack.end(), needle, needle+3, comp_case_insensitive); //if (it != haystack.end()) //{ // std::cout << "The first match is:" << *it << '\n'; //} return 0; } //-----Output----- //The first match is:A //The first match is:a
adjacent_find
template<class ForwardIterator> ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last) { if (first != last) { ForwardIterator next = first; ++next; while (next != last) { if (*first == next) { return first; } ++first; ++next; } } return last; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::adjacent_find #include <vector> // std::vector int main() { int myints[] = {5,20,5,30,30,20,10,10,20}; std::vector<int> myvector(myints, myints+8); std::vector<int>::iterator it; // using default comparison: it = std::adjacent_find(myvector.begin(), myvector.end()); if (it != myvector.end()) { std::cout << "The first pair of repeated elements are:" << *it << '\n'; } return 0; } //-----Output----- //The first pair of repeated elements are:30
count
template <class InputIterator, class T> int count(InputIterator first, InputIterator last, const T& val) { int ret = 0; while (first != last) { if (*first == val) { ++ret; } ++first; } return ret; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::count #include <vector> // std::vector int main() { // counting elements in array: int myints[] = {10,20,30,30,20,10,10,40}; // 8 elements int mycount = std::count(myints, myints+8, 10); std::cout << "10 appears " << mycount << " times.\n"; // counting elements in container: std::vector<int> myvector(myints, myints+8); mycount = std::count(myvector.begin(), myvector.end(), 20); std::cout << "20 appears " << mycount << " times.\n"; return 0; } //-----Output----- //10 appears 3 times. //20 appears 2 times.
count_if
template<class InputIterator, class UnaryPredicate> int countIf(InputIterator first, InputIterator last, UnaryPredicate pred) { int ret = 0; while (first != last) { if (pred(*first)) { ++ret; } ++first; } return ret; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::count_if #include <vector> // std::vector bool IsOdd(int i) { return ((i%2) == 1); } int main() { std::vector<int> myvector; for (int i=1; i<10; i++) { myvector.push_back(i); } int mycount = countIf(myvector.begin(), myvector.end(), IsOdd); std::cout << "myvector contains " << mycount << " odd values.\n"; return 0; } //-----Output----- //myvector contains 5 odd values.
mismatch
#include <utility> // std::pair template<class InputIterator1, class InputIterator2> std::pair<InputIterator1, InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) { while ((first1 != last1) && (first1 == first2)) { ++first1; ++first2; } return std::make_pair(first1, first2); } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::mismatch #include <vector> // std::vector bool mypredicate(int i, int j) { return (i==j); } int main() { std::vector<int> myvector; // 10 20 30 40 50 for (int i=1; i<6; i++) { myvector.push_back(i*10); } int myints[] = {10, 20, 80, 320, 1024}; std::pair<std::vector<int>::iterator, int*> mypair; // using defautl comparison: mypair = std::mismatch(myvector.begin(), myvector.end(), myints); std::cout << "First mismatching elements:" << *mypair.first; std::cout << " and " << *mypair.second << '\n'; ++mypair.first; ++mypair.second; // using predicate comparison: mypair = std::mismatch(mypair.first, myvector.end(), mypair.second, mypredicate); std::cout << "Second mismatching elements:" << *mypair.first; std::cout << " and " << *mypair.second << '\n'; return 0; } //------Output------ //First mismatching elements:30 and 80 //Second mismatching elements:40 and 320
equal
template<class InputIterator1, class InputIterator2> bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) { while (first1 != last1) { if (first1 != first2) { return false; } ++first1; ++first2; } return true; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::equal #include <vector> // std::vector bool mypredicate(int i, int j) { return (i==j); } int main() { int myints[] = {20,40,60, 80, 100}; std::vector<int> myvector(myints, myints+5); // using default comparison: if (std::equal(myvector.begin(), myvector.end(), myints)) { std::cout << "The contents of both sequences are equal.\n"; } else { std::cout << "The contents of both sequences differ.\n"; } myvector[3] = 81; // using predicate comparison: if (std::equal(myvector.begin(), myvector.end(), myints, mypredicate)) { std::cout << "Second contents of both sequences are equal.\n"; } else { std::cout << "Second contents of both sequences differ.\n"; } return 0; } //-----Putput----- //The contents of both sequences are equal. //Second contents of both sequence differ.
is_permutation
#include <iostream> // std::cout template <class InputIterator1, class InputIterator2> bool is_permutation(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) { std::tie(first1, first2) = std::mismatch(first1, last1, first2); if (first1 == last1) { return true; } InputIterator2 last2 = first2; std::advance(last2, std::distance(first1, last1)); for (InputIterator1 it1=first1; it1!=last1; ++it1) { if (std::find(first1, it1, *it1) == it1) { auto n = std::count(first2, last2, *it1); if (n==0 || std::count(it1, last1, *it1)!=n) { return false; } } } } //-----Example----- #include <algorithm> // std::is_permutation #include <array> // std::array int main() { std::array<int, 5> foo = {1,2,3,4,5}; std::array<int, 5> bar = {3,1,4,5,2}; if (std::is_permutation(foo.begin(), foo.end(), bar.begin())) { std::cout << "foo and bar contain the same elements.\n"; } return 0; } //------Output----- //foo and bar contain the same elements.
search
template<class ForwardIterator1, class ForwardIterator2> ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { if (first2 == last2) { return first1; } while (first1 != last1) { ForwardIterator1 it1 = first1; ForwardIterator2 it2 = first2; while(*it1 == *it2) { ++it1; ++it2; if (it2 == last2) { return first1; } if (it1 == last1) { return last1; } } ++first1; } return first1; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::search #include <vector> // std::vector bool mypredicate(int i, int j) { return (i==j); } int main() { std::vector<int> haystack; // 10 20 30 40 50 60 70 80 90 for (int i=1; i<10; ++i) { haystack.push_back(i*10); } // using default comparison: int needle1[] = {40, 50, 60, 70}; std::vector<int>::iterator it; it = std::search(haystack.begin(), haystack.end(), needle1, needle1+4); if (it != haystack.end()) { std::cout << "needle1 found at position:" << (it-haystack.begin()) << '\n'; } else { std::cout << "needle1 not found.\n"; } // using predicate comparison: int needle2[] = {20, 30, 50}; it = std::search(haystack.begin(), haystack.end(), needle2, needle2+3, mypredicate); if (it != haystack.end()) { std::cout << "needle2 found at position:" << (it-haystack.begin()) << '\n'; } else { std::cout << "needle2 not found.\n"; } return 0; } //-----Output----- //needle1 found at position:3 //needle2 not found.
search_n
#include <iostream> // std::cout template <class ForwardIterator, class Size, class T> ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Size count, const T& val) { ForwardIterator it, limit; Size i; limit = first; std::advance(limit, std::distance(first, last)-count); while (first != limit) { it = first; i = 0; while (*it == val) { ++it; if (++i == count) { return first; } } ++first; } return last; } //-----Example----- #include <algorithm> // std::searcn_n #include <vector> // std::vector bool mypredicate(int i, int j) { return (i==j); } int main() { int myints[] = {10,20,30,30,20,10,10,20}; std::vector<int> myvector(myints, myints+8); std::vector<int>::iterator it; // using default comparison: it = std::search_n(myvector.begin(), myvector.end(), 2, 30); if (it != myvector.end()) { std::cout << "Two 30s found at position:" << (it-myvector.begin()) << '\n'; } else { std::cout << "Match1 not found.\n"; } // using predicate comparison: it = std::search_n(myvector.begin(), myvector.end(), 2, 10, mypredicate); if (it != myvector.end()) { std::cout << "Two 10s found at position:" << (it-myvector.begin()) << '\n'; } else { std::cout << "Match2 not found.\n"; } return 0; } //-----Output----- //Two 30s found at position:2 //Two 10s found at position:5
2.更改原序列运算
copy
template<class InputIterator, class OutputInterator> OutputInterator copy(InputIterator first, InputIterator last, OutputInterator result) { while (first != last) { *result = *last; ++result; ++first; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::copy #include <vector> // std::vector int main() { int myints[] = {10,20,30,40,50,60,70}; std::vector<int> myvector(7); std::copy(myints, myints+7, myvector.begin()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 10 20 30 40 50 60 70
copy_n
template<class InputIterator, class Size, class OutputIterator> OutputIterator copy_n(InputIterator first, Size n, OutputIterator result) { while (n > 0) { *result = *first; ++result; ++first; --n; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::copy_n #include <vector> // std::vector int main() { int myints[] = {10,20,30,40,50,60,70}; std::vector<int> myvector; myvector.resize(7); std::copy_n(myints, 7, myvector.begin()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output---- //myvector contains: 10 20 30 40 50 60 70
copy_if
template<class InputIterator, class OutputIterator, class UnaryPredicate> OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred) { while (first != last) { if (pred(*first)) { *result = *first; ++result; } ++first; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::copy_if #include <vector> // std::vector int main() { std::vector<int> foo = {5, -10, -5, 0, 15}; std::vector<int> bar(foo.size()); // copy only positive numbers: auto it = std::copy_if(foo.begin(), foo.end(), bar.begin(), [](int i){return (i>0);}); bar.resize(std::distance(bar.begin(), it)); // shrink container to new size std::cout << "bar contains:"; for (int &x: bar) { std::cout << ' ' << x; } std::cout << '\n'; return 0; } //-----Output----- //bat contains: 5 15
copy_backward
template<class InputIterator, class OutputIterator> OutputIterator copy_backward(InputIterator first, InputIterator last, OutputIterator result) { while (last != first) { *(--result) = *(--last); } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::copy_backward #include <vector> // std::vector int main() { std::vector<int> myvector; // set some values: 10 20 30 40 50 for (int i=1; i<=5; ++i) { myvector.push_back(i*10); } std::vector<int> bar; bar.resize(myvector.size()); std::copy_backward(myvector.begin(), myvector.end(), bar.end()); std::cout << "bar contains:"; for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //bar contains: 10 20 30 40 50
move
#include <iostream> // std::cout #include <algorithm> // std::move(range) #include <utility> // std::move(object) #include <vector> // std::vector #include <string> // std::string template<class InputIterator, class OutputIterator> OutputIterator move(InputIterator first, InputIterator last, OutputIterator result) { while (first != last) { *result = std::move(*first); ++result; ++first; } return result; } //-----Example----- int main() { std::vector<std::string> foo = {"Hello", "World"}; std::vector<std::string> bar(2); // moving ranges: std::cout << "Moving ranges...\n"; std::move(foo.begin(), foo.end(), bar.begin()); std::cout << "foo contains " << foo.size() << " elements:"; std::cout << "(each in an unspecified but valid state)"; std::cout << '\n'; std::cout << "bar contains " << bar.size() << " elements:"; for (std::string &x:bar) { std::cout << " [" << x << "]"; } std::cout << '\n'; // moving containers: std::cout << "Moving containers...\n"; foo = std::move(bar); std::cout << "foo contains " << foo.size() << " elements:"; for (std::string &x:foo) { std::cout << " [" << x << "]"; } std::cout << '\n'; std::cout << "bar is in an unspecified but valid state"; std::cout << '\n'; return 0; } //-----Output----- //Moving ranges... //foo contains 2 elements:(each in an unspecified but valid state) //bar contains 2 elements: [Hello] [World] //Moving contains... //foo contains 2 elements: [Hello] [World] //bar is in an unspecified but valid state
move_backward
#include <iostream> // std::cout #include <algorithm> // std::move_backward #include <vector> // std::vector #include <string> // std::string template<class InputIterator, class OutputIterator> OutputIterator move_backward(InputIterator first, InputIterator last, OutputIterator result) { while (last != first) { *(--result) == *(--last); } return result; } //-----Example----- int main() { std::string elems[2] = {"Hello", "World"}; std::vector<std::string> bar(4); // insert new elements at the beginning: std::move_backward(elems, elems+2, bar.end()); bar[0] = "Welcome"; bar[1] = "To"; std::cout << "bar contains:"; for (std::string &x:bar) { std::cout << " [" << x << "]"; } std::cout << '\n'; return 0; } //-----Output----- //bar contains: [Welcome] [To] [Hello] [World]
swap
template<class T> void swap(T &a, T &b) { T c(a); a = b; b = c; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::swap #include <vector> // std::vector int main() { int x = 10; int y = 20; std::swap(x, y); std::cout << "Swap x and y:\n"; std::cout << "x=" << x << "; y=" << y; std::cout << '\n'; std::vector<int> foo(3,x); std::vector<int> bar(2,y); std::swap(foo, bar); std::cout << "Swap contains:\n"; std::cout << "foo contains:"; for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; std::cout << "bar contains:"; for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //Swap x and y: //x=20; y=10 //Swap contains: //foo contains:10 10 //bar contains:20 20 20
swap_ranges
#include <iostream> // std::cout #include <algorithm> // std::swap_ranges #include <vector> // std::vector template<class ForwardIterator1, class ForwardIterator2> ForwardIterator2 swap_ranges(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2) { while (first1 != last1) { std::swap(*first1, *first2); ++first1; ++first2; } return first2; } //-----Example----- int main() { std::vector<int> foo(5, 11); // 11 11 11 11 11 std::vector<int> bar(5, 22); // 22 22 22 22 22 std::swap_ranges(foo.begin()+1, foo.end()-1, bar.begin()+1); std::cout << "foo contains:"; for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; std::cout << "bar contains:"; for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //foo contains: 11 22 22 22 11 //bar contains: 22 11 11 11 22
iter_swap
#include <iostream> // std::cout #include <algorithm> // std::iter_swap #include <vector> // std::vector template<class ForwardIterator1, class ForwardIterator2> void iter_swap(ForwardIterator1 a, ForwardIterator2 b) { std::swap(*a, *b); } //-----Example----- int main() { int myints[] = {10,20,30,40,50}; // myints: 10 20 30 40 50 std::vector<int> myvector(4,99); // myvector: 99 99 99 99 std::iter_swap(myints, myvector.begin()); // myints: 99 20 30 40 50 // myvector: 10 99 99 99 std::iter_swap(myints+2, myvector.begin()+3); // myints: 99 20 99 40 50 // myvector: 10 99 99 30 std::cout << "myints contains:"; for (int i=0; i<5; i++) { std::cout << ' ' << myints[i]; } std::cout << '\n'; std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myints contains: 99 20 99 40 50 //myvector contains: 10 99 99 30
transform
template<class InputIterator, class OutputIterator, class UnaryOperator> OutputIterator transform(InputIterator first, InputIterator last, OutputIterator result, UnaryOperator op) { while (first != last) { *result = op(*first); ++result; ++first; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::transform #include <vector> // std::vector #include <functional> // std::plus int op_increase (int i) { return (++i); } int main() { std::vector<int> foo; std::vector<int> bar; // set some value:10 20 30 40 50 for (int i=1; i<=5; i++) { foo.push_back(i*10); } bar.resize(foo.size()); std::transform(foo.begin(), foo.end(), bar.begin(), op_increase); std::cout << "increase foo:"; for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; std::transform(foo.begin(), foo.end(), bar.begin(), bar.begin(), std::plus<int>()); std::cout << "plus foo and bar:"; for (std::vector<int>::iterator it= bar.begin(); it!=bar.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //icrease foo: 11 21 31 41 51 //plus foo and bar: 21 41 61 81 101
replace
template<class ForwardIterator, class T> void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) { while (first != last) { if (*first == old_value) { *first = new_value; } ++first; } } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::replace #include <vector> // std::vector int main() { int myints[] = {10, 20, 30, 20, 10}; std::vector<int> myvector(myints, myints+5); std::cout << "old myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; std::replace(myvector.begin(), myvector.end(), 20, 66); std::cout << "new myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //old myvector contains: 10 20 30 20 10 //new myvector contains: 10 66 30 66 10
replace_if
template<class ForwardIterator, class UnaryPredicate, class T> void replace_if(ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& new_value) { while (first != last) { if (pred(*first)) { *first = new_value; } ++first; } } //-----Excample----- #include <iostream> // std::cout #include <algorithm> // std::replace_if #include <vector> // std::vector bool IsOdd(int i) { return ((i%2) == 1); } int main() { std::vector<int> myvector; // 1 2 3 4 5 for (int i=1; i<6; i++) { myvector.push_back(i); } std::replace_if(myvector.begin(), myvector.end(), IsOdd, 0); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Example----- //myvector contains: 0 2 0 4 0
replace_copy
template<class InputIterator, class OutputIterator, class T> OutputIterator replace_copy(InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value) { while (first != last) { *result = (*first==old_value)?new_value:*first; ++first; ++result; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::replace_copy #include <vector> // std::vector int main() { int myints[] = {10,20,20,30,40,20}; std::vector<int> myvector(6); std::replace_copy(myints, myints+6, myvector.begin(), 20, 66); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 10 66 66 30 40 66
replace_copy_if
template<class InputIterator, class OutputIterator, class UnaryPredicate, class T> OutputIterator replace_copy_if(InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred, const T& new_value) { while (first != last) { *result = (pred(*first))?new_value:*first; ++result; ++first; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::replace_copy_if #include <vector> // std::vector bool IsOdd(int i) { return ((i%2)==1); } int main() { std::vector<int> foo, bar; for (int i=1; i<10; ++i) { foo.push_back(i); } bar.resize(foo.size()); std::replace_copy_if(foo.begin(), foo.end(), bar.begin(), IsOdd, 0); std::cout << "bar contains:"; for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //bar contains: 0 2 0 4 0 6 0 8 0
fill
template<class InputIterator, class T> void fill(InputIterator first, InputIterator last, const T& val) { while (first != last) { *first = val; ++first; } } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::fill #include <vector> // std::vector int main() { std::vector<int> myvector(8); std::fill(myvector.begin(), myvector.begin()+2, 1); std::fill(myvector.begin()+2, myvector.begin()+4, 2); std::fill(myvector.begin()+4, myvector.end(), 3); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 1 1 2 2 3 3 3 3
fill_n
template<class OutputIterator, class Size, class T> OutputIterator fill_n(OutputIterator first, Size n, const T& val) { while (n > 0) { *first = val; ++first; --n; } return first; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::fill_n #include <vector> // std::vector int main() { std::vector<int> myvector(8, 10); std::fill_n(myvector.begin(), 2, 20); std::fill_n(myvector.begin()+3, 3, 30); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 20 20 10 30 30 30 10 10
generate
template<class ForwardIterator, class Generator> void generate(ForwardIterator first, ForwardIterator last, Generator gen) { while (first != last) { *first = gen(); ++first; } } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::generate #include <vector> // std::vector #include <ctime> // std::time #include <cstdlib> // std::rand, std::srand // function generator: int RandomNumber() { return (std::rand()%100); } // class generator: struct c_unique{ int current; c_unique(){current=0;} int operator()(){return ++current;} }UniqueNumber; int main() { std::srand (unsigned(std::time(0))); std::vector<int> myvector(8); std::generate(myvector.begin(), myvector.end(), RandomNumber); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; std::generate(myvector.begin(), myvector.end(), UniqueNumber); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 57 87 76 66 85 54 17 15 //myvector contains: 1 2 3 4 5 6 7 8
generate_n
template<class OutputIterator, class Size, class Generator> void generate_n(OutputIterator first, Size n, Generator gen) { while (n > 0) { *first = gen(); ++first; --n; } } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::generate_n int current = 0; int UniqueNumber() { return ++current; } int main() { int myints[9]; std::generate_n(myints, 9, UniqueNumber); std::cout << "myints contains:"; for (int i=0; i<9; ++i) { std::cout << ' ' << myints[i]; } std::cout << '\n'; return 0; } //-----Output----- //myints contains: 1 2 3 4 5 6 7 8 9
remove
template<class ForwardIterator, class T> ForwardIterator Remove(ForwardIterator first, ForwardIterator last, const T& val) { ForwardIterator result = first; while (first != last) { if (!(*first == val)) { *result = *first; ++result; } ++first; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::remove int main() { int myints[] = {10,20,30,40,50,40,30,20,10}; int *pBegin = myints; int *pEnd = myints+sizeof(myints)/sizeof(int); pEnd = Remove(pBegin, pEnd, 20); std::cout << "rang contains:"; for (int *p=pBegin; p!=pEnd; ++p) { std::cout << ' ' << *p; } std::cout << '\n'; return 0; } //-----Output----- //rang contains: 10 30 40 50 40 30 10
remove_copy
template<class InputIterator, class OutputIterator, class T> OutputIterator remove_copy(InputIterator first, InputIterator last, OutputIterator result, const T& val) { while (first != last) { if (!(*first == val)) { *result = *first; ++result; } ++first; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::remove_copy #include <vector> // std::vector int main() { int myints[] = {10, 20, 30, 40, 30, 20, 10}; std::vector<int> myvector(7); std::remove_copy(myints, myints+7, myvector.begin(), 30); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //muvector contains: 10 20 40 20 10 0 0
remove_copy_if
template<class InputIterator, class OutputIterator, class UnaryPredicate> OutputIterator remove_copy_if(InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred) { while (first != last) { if (!pred(*first)) { *result = *first; ++result; } ++first; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::remove_copy_if #include <vector> // std::vector bool IsOdd(int i) { return ((i%2)==1); } int main() { int myints[] = {1,2,3,4,5,6,7,8,9}; std::vector<int> myvector(9); std::remove_copy_if(myints, myints+9, myvector.begin(), IsOdd); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 2 4 6 8 0 0 0 0 0
unique
template<class ForwardIterator> ForwardIterator unique(ForwardIterator first, ForwardIterator last) { if (first == last) { return last; } ForwardIterator result = last; while (++first != last) { if (!(*result != last)) { *(++result) = *first; } } return ++result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::unique #include <vector> // std::vector bool myfunction(int i, int j) { return (i == j); } int main() { int myints[] = {10,20,20,30,40,40,30,30}; std::vector<int> myvector(myints,myints+8); // using default comparition: std::vector<int>::iterator it; it = std::unique(myvector.begin(), myvector.end()); myvector.resize(std::distance(myvector.begin(),it)); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; std::vector<int> yvector(myints,myints+8); // using predicate comparison: std::unique(yvector.begin(), yvector.end(), myfunction); std::cout << "yvector contains:"; for (std::vector<int>::iterator it=yvector.begin(); it!=yvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 10 20 30 40 30 //yvector contains: 10 20 30 40 30 40 30 30
unique_copy
#include <iostream> // std::cout #include <algorithm> // std::unique_copy, std::sort, std::distance #include <vector> // std::vector template<class InputIterator, class OutputIterator> OutputIterator unique_copy(InputIterator first, InputIterator last, OutputIterator result) { if (first == last) { return result; } *result = *first; while (++first != last) { typename std::iterator_traits<InputIterator>::value_type val = *first; if (!(*result == val)) { *(++result) = val; } } return ++result; } //-----Example----- bool myfunction(int i, int j) { return (i==j); } int main() { int myints[] = {10,20,20,20,30,30,20,20,10}; std::vector<int> myvector(9); // using default comparison: std::vector<int>::iterator it; it = std::unique_copy(myints, myints+9, myvector.begin()); std::cout << "myvector contains:"; for (std::vector<int>::iterator i=myvector.begin(); i!=myvector.end(); ++i) { std::cout << ' ' << *i; } std::cout << '\n'; std::sort(myvector.begin(), it); std::cout << "sort myvector contains:"; for (std::vector<int>::iterator i=myvector.begin(); i!=myvector.end(); ++i) { std::cout << ' ' << *i; } std::cout << '\n'; // using predicate comparison: it = std::unique_copy(myvector.begin(), it, myvector.begin(), myfunction); myvector.resize(std::distance(myvector.begin(), it)); std::cout << "predicate myvector contains:"; for (std::vector<int>::iterator i=myvector.begin(); i!=myvector.end(); ++i) { std::cout << ' ' << *i; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 10 20 30 20 10 0 0 0 0 //sort myvector contains: 10 10 20 20 30 0 0 0 0 //predicate myvector contains: 10 20 30
reverse
#include <iostream> // std::cout #include <algorithm> // std::reverse #include <vector> // std::vector template<class InputIterator> void reverse(InputIterator first, InputIterator last) { while ((first != last) && (first != --last)) { std::iter_swap(first, last); ++first; } } //-----Example----- int main() { std::vector<int> myvector; for (int i=1; i<10; i++) { myvector.push_back(i); } std::reverse(myvector.begin(), myvector.end()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains:9 8 7 6 5 4 3 2 1
reverse_copy
template<class InputIterator, class OutputIterator> OutputIterator reverse_copy(InputIterator first, InputIterator last, OutputIterator result) { while (first != last) { --last; *result = *last; ++result; } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::reverse_copy #include <vector> // std::vector int main() { int myints[] = {1,2,3,4,5,6,7,8,9}; std::vector<int> myvector; myvector.resize(9); std::reverse_copy(myints, myints+9, myvector.begin()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 9 8 7 6 5 4 3 2 1
rotate
#include <iostream> // std::cout #include <algorithm> // std::rotate #include <vector> // std::vector template<class ForwardIterator> void rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last) { ForwardIterator next = middle; while (first != next) { swap(*first++, *next++); if (next == last) { next = middle; } else if (first == middle) { middle = next; } } } //-----Example----- int main() { std::vector<int> myvector; for (int i=1; i<10; ++i) { myvector.push_back(i); } std::rotate(myvector.begin(), myvector.begin()+3, myvector.end()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 4 5 6 7 8 9 1 2 3
rotate_copy
#include <iostream> // std::cout #include <algorithm> // std::rotate_copy #include <vector> // std::vector template<class InputIterator, class OutputIterator> OutputIterator rotate_copy(InputIterator first, InputIterator middle, InputIterator last, OutputIterator result) { result = std::copy(middle, last, result); result = std::copy(first, middle, result); return result; } //-----Example----- int main() { int myints[] = {1,2,3,4,5,6,7,8,9}; std::vector<int> myvector(9); std::rotate_copy(myints, myints+4, myints+9, myvector.begin()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 5 6 7 8 9 1 2 3 4
random_shuffle
#include <iostream> // std::cout #include <algorithm> // std::random_shuffle #include <vector> // std::vector #include <ctime> // std::time #include <cstdlib> // std::rand, std::srand template<class RandomAccessIterator, class RandomNumberGenerator> void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator &gen) { typename std::iterator_traits<RandomAccessIterator>::difference_type i, n; n = (last-first); for (i=n-1; i>0; --i) { std::swap(first[i], first[gen(i+1)]); } } //-----Example----- int myrandom(int i) { return std::rand()%i; } int main() { std::srand(unsigned(std::time(0))); std::vector<int> myvector; for (int i=1; i<10; i++) { myvector.push_back(i); } // using built-in random generator: std::random_shuffle(myvector.begin(), myvector.end()); std::cout << "def-random contain:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; // using myrandom std::random_shuffle(myvector.begin(), myvector.end(), myrandom); std::cout << "sef-random contain:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //def-random contain: 7 8 4 2 6 3 5 1 9 //sef-random contain: 6 1 9 8 4 3 7 5 2
shuffle
#include <iostream> // std::cout #include <algorithm> // std::shuffle #include <array> // std::array #include <random> // std::default_random_engine #include <chrono> // std::chrono::system_clock template<class RandomAccessIterator, class URNG> void Shuffle(RandomAccessIterator first, RandomAccessIterator last, URNG &&g) { for (auto i=(last-first)-1; i>0; --i) { std::uniform_int_distribution<decltype(i)> d(0, i); std::swap(first[i], first[d(g)]); } } //-----Example----- int main() { std::array<int, 5> foo{1,2,3,4,5}; unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); Shuffle(foo.begin(), foo.end(), std::default_random_engine(seed)); std::cout << "shuffled elements:"; for (int &x:foo) { std::cout << ' ' << x; } std::cout << '\n'; return 0; } //-----Output----- //shuffled elements: 3 1 4 2 5
3.分割运算
is_partitioned
template <class InputIterator, class UnaryPredicate> bool is_partitioned(InputIterator first, InputIterator last, UnaryPredicate pred) { while (first!=last && pred(*first)) { ++first; } while (first != last) { if (pred(*first)) { return false; } ++first; } return true; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::is_partitioned #include <array> // std::array bool IsOdd(int i) { return (i%2)==1; } int main() { std::array<int,7> foo{1,2,3,4,5,6,7}; std::cout << "foo:"; for (int &x:foo) { std::cout << ' ' << x; } if (std::is_partitioned(foo.begin(), foo.end(), IsOdd)) { std::cout << " (partitioned)\n"; } else { std::cout << " (not partitioned)\n"; } std::partition(foo.begin(), foo.end(), IsOdd); std::cout << "foo:"; for (int &x:foo) { std::cout << ' ' << x; } if (std::is_partitioned(foo.begin(), foo.end(), IsOdd)) { std::cout << " (partitioned)\n"; } else { std::cout << " (not partitioned)\n"; } return 0; } //-----Output----- //foo: 1 2 3 4 5 6 7 (not partitioned) //foo: 1 7 3 5 4 6 2 (partitioned)
partition
#include <iostream> // std::cout #include <algorithm> // std::partition #include <vector> // std::vector template<class InputIterator, class UnaryPredicate> InputIterator partition(InputIterator first, InputIterator last, UnaryPredicate pred) { while (first != last) { while (pred(*first)) { ++first; } if (first == last) { return first; } do { --last; if (first == last) { return first; } }while (!pred(*last)); swap(*first, *last); ++first; } return first; } //-----Example----- bool IsOdd(int i) { return (i%2)==1; } int main() { std::vector<int> myvector; for (int i=1; i<10; ++i) { myvector.push_back(i); } std::vector<int>::iterator bound; bound = std::partition(myvector.begin(), myvector.end(), IsOdd); std::cout << "odd elements:"; for (std::vector<int>::iterator it=myvector.begin(); it!=bound; ++it) { std::cout << ' ' << *it; } std::cout << '\n'; std::cout << "even elements:"; for (std::vector<int>::iterator it2=bound; it2!=myvector.end(); ++it2) { std::cout << ' ' << *it2; } std::cout << '\n'; return 0; } //-----Output----- //odd elements: 1 9 3 7 5 //even elements: 6 4 8 2
stable_sort
#include <iostream> // std::cout #include <algorithm> // std::stable_partition #include <string> // std::string bool myfunction(char c) { return c=='*'; } int main() { std::string str = "***b**a**c**d**"; std::string str1(str); std::string str2(str); std::partition(std::begin(str1), std::end(str1), myfunction); std::stable_partition(std::begin(str2), std::end(str2), myfunction); std::cout << "partition string=" << str1.c_str() << '\n'; std::cout << "stable_partition string=" << str2.c_str() << '\n'; return 0; } //-----Output----- //partition string=*************cdab //stable_partititon string=***********bacd
partition_copy
#include <iostream> // std::cout #include <algorithm> // std::partition_copy #include <vector> // std::vector template <class InputIterator, class OutputIterator1, class OutputIterator2, class UnaryPredicate> std::pair<OutputIterator1, OutputIterator2> partition_copy(InputIterator first, InputIterator last, OutputIterator1 result_true, OutputIterator2 result_false, UnaryPredicate pred) { while (first != last) { if (pred(*first)) { *result_true = *first; ++result_true; } else { *result_false = *first; ++result_false; } ++first; } return std::make_pair(result_true, result_false); } //-----Example----- bool IsOdd(int i) { return (i%2)==1; } int main() { std::vector<int> foo{1,2,3,4,5,6,7,8,9}; std::vector<int> odd,even; unsigned n = std::count_if(foo.begin(), foo.end(), IsOdd); odd.resize(n); even.resize(foo.size()-n); std::partition_copy(foo.begin(), foo.end(), odd.begin(), even.begin(), IsOdd); std::cout << "odd:"; for (int &x:odd) { std::cout << ' ' << x; } std::cout << '\n'; std::cout << "even:"; for (int &y:even) { std::cout << ' '<< y; } std::cout << '\n'; return 0; } //-----Output----- //odd: 1 3 5 7 9 //even: 2 4 6 8
partition_point
#include <iostream> // std::cout #include <algorithm> // std::partition std::partition_point #include <vector> // std::vector template<class InputIterator, class UnaryPredicate> InputIterator partition_point(InputIterator first, InputIterator last, UnaryPredicate pred) { auto n = std::distance(first, last); while (n > 0) { InputIterator it = first; auto step = n/2; std::advance(it, step); if (pred(*first)) { first = ++it; n -= step+1; } else { n = step; } } return first; } //-----Example----- bool IsOdd(int i) { return (i%2)==1; } int main() { std::vector<int> foo{1,2,3,4,5,6,7,8,9}; std::vector<int> odd; std::partition(foo.begin(), foo.end(), IsOdd); auto it = std::partition_point(foo.begin(), foo.end(), IsOdd); odd.assign(foo.begin(), it); std::cout << "odd:"; for (int &x:odd) { std::cout << ' ' << x; } std::cout << '\n'; return 0; } //-----Output----- //odd: 1 3 5 7 9
4.排序
sort
#include <iostream> // std::cout #include <algorithm> // std::sort #include <vector> // std::vector bool myfunction(int i, int j) { return (i<j); } struct myclass { bool operator()(int i, int j) { return (i<j); } }myobject; int main() { int myints[] = {32,71,12,45,26,80,53,33}; std::vector<int> myvector(myints, myints+8); // 32 71 12 45 26 80 53 33 std::sort(myvector.begin(),myvector.begin()+4); //(12 32 45 71)26 80 53 33 std::sort(myvector.begin()+4,myvector.end(),myfunction);//(12 32 45 71(26 33 53 80) std::sort(myvector.begin(),myvector.end(),myobject); //(12 26 32 33 45 53 71 80) std::cout << "myvector contains:"; for (std::vector<int>::iterator it= myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 12 26 32 33 45 53 71 80
partial_sort
#include <iostream> // std::cout #include <algorithm> // std::partial_sort #include <vector> // std::vector bool myfunction(int i, int j) { return (i<j); } int main() { int myints[] = {9,8,7,6,5,4,3,2,1}; std::vector<int> myvector(myints, myints+9); std::partial_sort(myvector.begin(), myvector.begin()+5, myvector.end()); std::partial_sort(myvector.begin(), myvector.begin()+5, myvector.end(), myfunction); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 1 2 3 4 5 9 8 7 6
partial_sort_copy
#include <iostream> // std::cout #include <algorithm> // std::partial_sort_copy #include <vector> // std::vector bool myfunction(int i, int j) { return (i<j); } int main() { int myints[] = {9,8,7,6,5,4,3,2,1}; std::vector<int> myvector(5); std::partial_sort_copy(myints, myints+9, myvector.begin(), myvector.end()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; //std::partial_sort_copy(myints, myints+9, myvector.begin(), myvector.end(), myfunction); //std::cout << "myvector_self contains:"; //for (std::vector<int>::iterator it2=myvector.begin(); it2!=myvector.end(); it2++) //{ // std::cout << ' ' << it2; //} //std::cout << '\n'; return 0; } //------Output----- //myvector contains: 1 2 3 4 5 //myvector_self contains: 1 2 3 4 5
is_sorted
template<class InputInterator> bool is_sorted(InputInterator first, InputInterator last) { if (first == last) { return true; } InputInterator next = first; while (++next != last) { if (*next < *first) { return false; } ++first; } return true; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::is_sorted, std::prev_permutation #include <array> // std::array int main() { std::array<int, 4> foo{2,4,1,3}; do{ std::prev_permutation(foo.begin(), foo.end()); std::cout << "foo:"; for (int &x:foo) { std::cout << ' ' << x; } std::cout << '\n'; }while (!std::is_sorted(foo.begin(),foo.end())); std::cout << "the range is sorted!\n"; return 0; } //foo: 1 2 3 4 //the range is sorted!
is_sorted_until
template<class InputIterator> InputIterator is_sorted_until(InputIterator first, InputIterator last) { if (first == last) { return first; } InputIterator next = first; while (++next != last) { if (*next < *first) { return next; } ++first; } return last; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::is_sorted_until, std::prev_permutation #include <array> // std::array int main() { std::array<int, 4> foo{2,4,1,3}; std::array<int, 4>::iterator it; do{ std::prev_permutation(foo.begin(), foo.end()); std::cout << "foo:"; for (int &x:foo) { std::cout << ' ' << x; } it = std::is_sorted_until(foo.begin(), foo.end()); std::cout << " (" << (it-foo.begin()) << " elements sorted)\n"; }while (it != foo.end()); std::cout << "the range is sorted!\n"; return 0; } //-----Output----- //foo: 1 2 3 4 (4 elements sorted) //the range is sorted!
nth_element
#include <iostream> // std::cout #include <algorithm> // std::nth_element, std::random_shuffle #include <vector> // std::vector bool myfunction(int i, int j) { return (i<j); } int main() { std::vector<int> myvector; for (int i=1; i<10; ++i) { myvector.push_back(i); } std::random_shuffle(myvector.begin(), myvector.end()); // using default comparison std::nth_element(myvector.begin(), myvector.begin()+5, myvector.end()); // using self function std::nth_element(myvector.begin(), myvector.begin()+5, myvector.end(), myfunction); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 1 2 3 4 5 6 7 8 9
5.二进制搜索
lower_bound upper_bound
#include <iostream> // std::cout #include <algorithm> // std::lower_bound, std::upper_bound, std::sort #include <vector> // std::vector template<class InputIterator, class T> InputIterator lower_bound(InputIterator first, InputIterator last, const T& val) { InputIterator it; typename std::iterator_traits<InputIterator>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count/2; std::advance(it, step); if (*it < val) { first = ++it; count -= step+1; } else { count = step; } } return first; } template<class InputIterator, class T> InputIterator upper_bound(InputIterator first, InputIterator last, const T& val) { InputIterator it; typename std::iterator_traits<InputIterator>::difference_type count, step; count = std::distance(first, last); while (count > 0) { it = first; step = count/2; std::advance(it, step); if (*it > val) { first = ++it; count -= step+1; } else { count = step; } } return first; } //-----Example----- int main() { int myints[] = {10,20,30,30,20,10,10,20}; std::vector<int> myvector(myints, myints+8); std::sort(myvector.begin(), myvector.end()); std::vector<int>::iterator low,up; low = std::lower_bound(myvector.begin(), myvector.end(), 20); up = std::upper_bound(myvector.begin(), myvector.end(), 20); std::cout << "lower_bound at position:" << (low-myvector.begin()) << '\n'; std::cout << "upper_bound at position:" << (up-myvector.begin()) << '\n'; return 0; } //-----Output----- //lower_bound at position:3 //upper_bound at position:6
equal_range
#include <iostream> // std::cout #include <algorithm> // std::equal_range, std::sort #include <vector> // std::vector template<class InputIterator, class T> std::pair<InputIterator, InputIterator> equal_range(InputIterator first, InputIterator last, const T& val) { InputIterator it = std::lower_bound(first, last, val); return std::make_pair(it, std::upper_bound(it, last, val)); } //-----Example----- bool mygreater(int i, int j) { return (i>j); } int main() { int myints[] = {10,20,30,30,20,10,10,20}; std::vector<int> myvector(myints, myints+8); std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds; std::sort(myvector.begin(), myvector.end()); // using default comparison: bounds = std::equal_range(myvector.begin(), myvector.end(), 20); std::sort(myvector.begin(), myvector.end(), mygreater); // using self conparison: bounds = std::equal_range(myvector.begin(), myvector.end(), 20, mygreater); std::cout << "bounds at positions:" << (bounds.first-myvector.begin()) << " and " << (bounds.second-myvector.begin()) << '\n'; return 0; } //-----Output----- //bounds at positions:2 and 5
binary_search
#include <iostream> // std::cout #include <algorithm> // std::binary_search, std::sort #include <vector> // std::vector template<class InputIterator, class T> bool binary_search(InputIterator first, InputIterator last, const T& val) { first = std::lower_bound(first, last, val); return ((first!=last) && !(val<*first)); } //-----Example----- bool myfunction(int i, int j) { return (i<j); } int main() { int myints[] = {1,2,3,4,5,4,3,2,1}; std::vector<int> myvector(myints,myints+9); // using default std::sort(myvector.begin(), myvector.end()); std::cout << "looking for 3..."; if (std::binary_search(myvector.begin(),myvector.end(), 3)) { std::cout << " found!\n"; } else { std::cout << " not found!\n"; } // using self std::sort(myvector.begin(), myvector.end(),myfunction); std::cout << "looking for 6..."; if (std::binary_search(myvector.begin(), myvector.end(), 6, myfunction)) { std::cout << " found!\n"; } else { std::cout << " not found!\n"; } return 0; } //-----Output----- //looking for 3... found! //looking for 6... not found!
6.合并运算
Merge
#include <iostream> // std::cout #include <algorithm> // std::merge, std::sort #include <vector> // std::vector template<class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while (true) { if (first1 == last1) { return (std::copy(first2, last2, result)); } if (first2 == last2) { return (std::copy(first1, last1, result)); } *result++ = (*first2<*first1)?*first2++:*first1++; } } //-----Example----- int main() { int array1[] = {5,10,15,20,25}; int array2[] = {1,11,21,31,41}; std::vector<int> myvector(10); std::sort(array1,array1+5); std::sort(array2,array2+5); std::merge(array1, array1+5, array2, array2+5, myvector.begin()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 1 5 10 11 15 20 21 25 31 41
inplace_merge
#include <iostream> // std::cout #include <algorithm> // std::inplace_merge, std::sort #include <vector> // std::vector int main() { int array1[] = {5,10,15,20,25}; int array2[] = {41,31,21,11,1}; std::vector<int> myvector(10); std::sort(array1, array1+5); std::sort(array2, array2+5); std::vector<int>::iterator it; it = std::copy(array1, array1+5, myvector.begin()); std::copy(array2, array2+5, it); std::inplace_merge(myvector.begin(), myvector.begin()+5, myvector.end()); std::cout << "myvector contains:"; for (std::vector<int>::iterator it2=myvector.begin(); it2!=myvector.end(); ++it2) { std::cout << ' ' << *it2; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains:1 5 10 11 15 20 21 25 31 41
includes
template<class InputIterator1, class InputIterator2> bool includes(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2) { while (first1!=last1 && first2!=last2) { if (*first2 < *first1) { return false; } else if (*first1 < *first2) { ++first1; } else { ++first1; ++first2; } } return first2==first1; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::includes, std::sort bool myfunction(int i, int j) { return i<j; } int main() { int array[] = {5,10,15,20,25,30,35,40,45,50}; int subarray[] = {40,30,20,10}; std::sort(array, array+10); std::sort(subarray, subarray+4); // using default if (std::includes(array, array+10, subarray, subarray+4)) { std::cout << "first array includes subarray!\n"; } else { std::cout << "first not includes!\n"; } // using self if (std::includes(array, array+10, subarray, subarray+4, myfunction)) { std::cout << "second array includes subarray!\n"; } else { std::cout << "second not includes!\n"; } return 0; } //-----Output----- //first array includes subarray //second array includes subarray
set_union
#include <iostream> // std::cout #include <algorithm> // std::set_union, std::sort #include <vector> // std::vector template<class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator set_union(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while (true) { if (first1 == last1) { std::copy(first2, last2, result); } if (first2 == last2) { std::copy(first1, last1, result); } if (*first1 < *first2) { *result = *first1; ++first1; } else if (*first2 < *first1) { *result = *first2; ++first2; } else { *result = *first1; ++first1; ++first2; } ++result; } return result; } //-----Example----- int main() { int firstArray[] = {5,10,15,20,25}; int secondArray[] = {10,20,30,40,50}; std::vector<int> myvector(10); std::vector<int>::iterator it; std::sort(firstArray, firstArray+5); std::sort(secondArray, secondArray+5); it = std::set_union(firstArray, firstArray+5, secondArray, secondArray+5, myvector.begin()); myvector.resize(it-myvector.begin()); std::cout << "myvector contains:"; for (it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 5 10 15 20 25 30 40 50
set_intersection
template<class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator set_intersection(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while (first1!=last1 && first2!=last2) { if (*first1 < *first2) { ++first1; } else if (*first2 < *first1) { ++first2; } else { *result = *first1; ++first1; ++first2; ++result; } } return result; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::set_intersection, std::sort #include <vector> // std::vector int main() { int firstArray[] = {5,10,15,20,25}; int secondArray[] = {10,20,30,40,50}; std::vector<int> myvector(10); std::sort(firstArray, firstArray+5); std::sort(secondArray, secondArray+5); std::vector<int>::iterator it; it = std::set_intersection(firstArray, firstArray+5, secondArray, secondArray+5, myvector.begin()); myvector.resize(it-myvector.begin()); std::cout << "myvector contains:"; for (it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 10 20
set_difference
#include <iostream> // std::cout #include <algorithm> // std::set_difference, std::sort #include <vector> // std::vector template<class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while (first1!=last1 && first2!=last2) { if (*first1 < *first2) { *result = *first1; ++result; ++first1; } else if (*first2 < *first1) { ++first2; } else { ++first1; ++first2; } } return std::copy(first1, last1, result); } //-----Example----- int main() { int firstArray[] = {10,20,30,40,50}; int secondArray[] = {5,10,15,20,25}; std::vector<int> myvector(10); std::sort(firstArray, firstArray+5); std::sort(secondArray, secondArray+5); std::vector<int>::iterator it; it = std::set_difference(firstArray, firstArray+5, secondArray, secondArray+5, myvector.begin()); myvector.resize(it-myvector.begin()); std::cout << "myvector contains:"; for (it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 30 40 50
set_symmetric_difference
#include <iostream> // std::cout #include <algorithm> // std::set_symmetric_difference, std::sort #include <vector> // std::vector template<class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while(true) { if (first1 == last1) { return std::copy(first2, last2, result); } if (first2 == last2) { return std::copy(first1, last1, result); } if (*first1 < *first2) { *result = *first1; ++result; ++first1; } else if (*first2 < *first1) { *result = *first2; ++result; ++first2; } else { ++first1; ++first2; } } } //-----Example----- int main() { int firstArray[] = {5,10,15,20,25}; int secondArray[] = {10,20,30,40,50}; std::vector<int> myvector(10); std::sort(firstArray, firstArray+5); std::sort(secondArray, secondArray+5); std::vector<int>::iterator it; it = std::set_symmetric_difference(firstArray, firstArray+5, secondArray, secondArray+5, myvector.begin()); myvector.resize(it-myvector.begin()); std::cout << "myvector contains:"; for (it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //myvector contains:5 15 25 30 40 50
7.堆运算
make_heap pop_heap is_heap
#include <iostream> // std::cout #include <algorithm> // std::is_heap, std::make_heap, std::pop_heap #include <vector> // std::vector int main() { std::vector<int> myvector{2,4,6,8,1,3,5,7,9}; if (!std::is_heap(myvector.begin(), myvector.end())) { std::make_heap(myvector.begin(), myvector.end()); } std::cout << "myvector contains:"; while (!myvector.empty()) { std::pop_heap(myvector.begin(), myvector.end()); std::cout << ' ' << myvector.back(); myvector.pop_back(); } std::cout << '\n'; return 0; } //-----Output----- //myvector contains: 1 2 3 4 5 6 7 8 9
is_head_until
#include <iostream> // std::cout #include <algorithm> // std::is_heap_until, std::sort, std::reverse #include <vector> // std::vector int main() { std::vector<int> myvector{2,4,6,8,9,7,5,3,1}; std::sort(myvector.begin(), myvector.end()); std::reverse(myvector.begin(), myvector.end()); auto last = std::is_heap_until(myvector.begin(), myvector.end()); std::cout << "The " << (last-myvector.begin()) << " first elements are a valid heap:"; for (auto it=myvector.begin(); it!=myvector.end(); ++it) { std::cout << ' ' << *it; } std::cout << '\n'; return 0; } //-----Output----- //The 9 first elements are a valid heap: 9 8 7 6 5 4 3 2 1
8.最小/最大运算
min
template<class T> const T& min(const T& a, const T& b) { return !(b<a)?a:b; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::min int main() { std::cout << "min(1,2)==" << std::min(1,2) << '\n'; std::cout << "min(2,1)==" << std::min(2,1) << '\n'; std::cout << "min('a','z')==" << std::min('a','z') << '\n'; std::cout << "min(3.14,2.72)==" << std::min(3.14,2.72) << '\n'; return 0; } //-----Output----- //min(1,2)==1 //min(2,1)==1 //min('a','z')==a //min(3.14,2.72)==2.72
minmax
#include <iostream> // std::cout #include <algorithm> // std::minmax template<class T> std::pair<const T&, const T&> minmax(const T& a, const T&b) { return (b<a)?std::make_pair(b,a):std::make_pair(a,b); } int main () { auto result = std::minmax({1,3,5,7,9}); std::cout << "minmax({1,3,5,7,9}): "; std::cout << result.first << ' ' << result.second << '\n'; return 0; } //-----Output----- //minmax({1,3,5,7,9}): 1 9
min_element max_element
template<class InputIterator> InputIterator min_element(InputIterator first, InputIterator last) { if (first == last) { return last; } InputIterator smallest = first; while(++first != last) { if (*first < *smallest) { smallest = first; } } return smallest; } //-----Example----- #include <iostream> // std::cout #include <algorithm> // std::min_element, std::max_element bool myfunction(int i, int j) { return i<j; } struct myclass { bool operator()(int i, int j) { return i<j; } }myobj; int main() { int myints[] = {3,7,2,5,6,8,4,1,9}; std::cout << "min_element:" << *std::min_element(myints, myints+9) << '\n'; std::cout << "max_element:" << *std::max_element(myints, myints+9) << '\n'; std::cout << "min_element1:" << *std::min_element(myints, myints+9, myfunction) << '\n'; std::cout << "max_element1:" << *std::max_element(myints, myints+9, myfunction) << '\n'; std::cout << "min_element2:" << *std::min_element(myints, myints+9, myobj) << '\n'; std::cout << "max_element2:" << *std::max_element(myints, myints+9, myobj) << '\n'; return 0; } //-----Output----- //min_element:1 //max_element:9 //min_element1:1 //max_element1:9 //min_element2:1 //max_element3:9
minmax_element
#include <iostream> // std::cout #include <algorithm> // std::minmax_element #include <vector> // std::vector int main() { std::vector<int> myvector{3,5,7,9,2,4,6,8,1}; auto result = std::minmax_element(myvector.begin(), myvector.end()); std::cout << "min_element is " << *result.first; std::cout << " and position at " << result.first-myvector.begin() << '\n'; std::cout << "max_element is " << *result.second; std::cout << " and postion at " << result.second-myvector.begin() << '\n'; return 0; } //-----Output----- //min_element is 1 and position at 8 //max_element is 9 and position at 3
9.其他
lexicographical
#include <iostream> // std::cout #include <algorithm> // std::lexicographical_compare #include <cctype> // std::tolower bool mycompare(char c1, char c2) { return std::tolower(c1)<std::tolower(c2); } int main() { char foo[] = "Apple"; char bar[] = "apartment"; std::cout << "def_compare:" << std::lexicographical_compare(foo, foo+5, bar, bar+9) << '\n'; std::cout << "self_compare:" << std::lexicographical_compare(foo, foo+5, bar, bar+9, mycompare) << '\n'; return 0; } //-----Output----- //def_compare:1 //self_compare:0
next_permutation
#include <algorithm> // std::next_permutation, std::sort int main() { int myints[] = {1,2,3}; std::sort(myints, myints+3); std::cout << "{1,2,3} permutation:\n"; do { std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n'; }while(std::next_permutation(myints, myints+3)); std::cout << "After loop:" << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n'; return 0; } //-----Output----- //{1,2,3} permutation: //1 2 3 //1 3 2 //2 1 3 //2 3 1 //3 1 2 //3 2 1 //After loop:1 2 3
prev_permutation
#include <iostream> // std::cout #include <algorithm> // std::prev_permutation, std::sort, std::reverse int main() { int myints[] = {1,2,3}; std::sort(myints, myints+3); std::reverse(myints, myints+3); std::cout << "{1,2,3} prev_permutation:" << '\n'; do{ std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n'; }while(std::prev_permutation(myints, myints+3)); std::cout << "After loop:" << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n'; return 0; } //-----Output----- //{1,2,3} prev_permutation: //3 2 1 //3 1 2 //2 3 1 //2 1 3 //1 3 2 //1 2 3 //After loop:3 2 1