C++頭文件algorithm中的函數(shù)功能詳解
C++中的算法都是通過函數(shù)模板實(shí)現(xiàn),所以STL的數(shù)據(jù)結(jié)構(gòu),甚至是自己定義的數(shù)據(jù)結(jié)構(gòu)基本都可以調(diào)用內(nèi)置算法。掌握C++內(nèi)置算法,可以幫助我們節(jié)省大量的時(shí)間!
1. 不修改內(nèi)容的序列操作
(1)all_of
查找是否所有元素滿足條件。
在range[first,last)中,所有pred都為真,或者range范圍為空,返回true,否則返回false。
template <class InputIterator, class UnaryPredicate> bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
舉例:
#include <iostream> // std::cout
#include <algorithm> // std::all_of
#include<list>
int main () {
//std::array<int,8> foo = {3,5,7,11,13,17,19,23};
std::list<int> foo = {3,5,7,11,13,17,19,23};
if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
std::cout << "All the elements are odd numbers.\n";//奇數(shù)
return 0;
}
(2)any_of
查找是否有元素滿足條件。
在range[first,last)中,pred至少有一個(gè)為真,或者range范圍為空,返回true,否則返回false。用法同all_of。
template <class InputIterator, class UnaryPredicate> bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
(3)none_of
查找是否所有元素都不滿足條件。
在range[first,last)中,pred沒有一個(gè)為真,或者range范圍為空,返回true,否則返回false。用法同all_of。
template <class InputIterator, class UnaryPredicate> bool none_of (InputIterator first, InputIterator last, UnaryPredicate pred);
(4)for_each
對range [first,last)中的每一個(gè)元素,都執(zhí)行fn函數(shù)操作。
- fn可以是普通函數(shù)也可以是仿函數(shù)(函數(shù)對象)。
- fn后面不可以添加括號
template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function fn);
代碼舉例:
#include <iostream> // std::cout
#include <algorithm> // std::for_each
#include <vector> // std::vector
void myfunction (int i) { // function:普通函數(shù)
std::cout << ' ' << i;
}
struct myclass { // function object type:,仿函數(shù),或者函數(shù)對象
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:";
for_each (myvector.begin(), myvector.end(), myfunction);
std::cout << '\n';
// or:
std::cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
std::cout << '\n';
return 0;
}
(5)find
查找第一個(gè)和所提供變量相同的元素。
從 range [first,last)依次尋找元素,如果找到第一個(gè)與val相同相同的元素,則返回它的迭代器,否則返回last的迭代器。
template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val);
代碼示例:
#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);
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);
if (it != myvector.end())
std::cout << "Element found in myvector: " << *it << '\n';
else
std::cout << "Element not found in myvector\n";
return 0;
}
輸出:
Element found in myints: 30
Element found in myvector: 30
(6)find_if
查找第一個(gè)滿足條件的元素。
從 range [first,last)依次尋找元素,如果找到第一個(gè)使得pred為真的元素,則返回它的迭代器,否則返回last迭代器。
template <class InputIterator, class UnaryPredicate> InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
代碼舉例:
尋找第一個(gè)奇數(shù)
#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';//奇數(shù)
return 0;
}
輸出:
The first odd value is 25
(7)find_if_not
查找第一個(gè)不滿足條件的元素。
從 range [first,last)依次尋找元素,如果找到第一個(gè)使得pred為假的元素,則返回它的迭代器,否則返回last迭代器。
template <class InputIterator, class UnaryPredicate> InputIterator find_if_not (InputIterator first, InputIterator last, UnaryPredicate pred);
代碼舉例:
尋找第一個(gè)偶數(shù)
#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;
}
輸出:
The first even value is 2
(8)find_end
模板1:查找最后一個(gè)相同的序列。
在range [first1,last1) 去尋找[first2,last2)的元素,如果找到最后一個(gè)(不是第一個(gè))被匹配的元素,則范圍第一個(gè)被匹配的迭代器,否則范圍last1的迭代器。
模板2:查找最后一個(gè)滿足條件的序列。
在range [first1,last1) 去尋找[first2,last2)的元素,如果找到最后一個(gè)(不是第一個(gè))滿足pred條件的元素,則范圍第一個(gè)被匹配的迭代器,否則范圍last1的迭代器。
//equality (1)
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2);
//predicate (2)
template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2,
BinaryPredicate pred);
代碼示例:
#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;
}
輸出:
needle1 last found at position 5
needle2 last found at position 3
(9)find_first_of
和find_end類似,只不過它是尋找第一個(gè)匹配的元素。
//equality (1)
template <class InputIterator, class ForwardIterator>
InputIterator find_first_of (InputIterator first1, InputIterator last1,
ForwardIterator first2, ForwardIterator last2);
//predicate (2)
template <class InputIterator, class ForwardIterator, class BinaryPredicate>
InputIterator find_first_of (InputIterator first1, InputIterator last1,
ForwardIterator first2, ForwardIterator last2,
BinaryPredicate pred);
(10)adjacent_find
模板1:從范圍 range [first,last)中尋找連續(xù)相同元素。
模板2:找到滿足條件pred的迭代器。
如果找到,則范圍范圍內(nèi)的第一個(gè)滿足的迭代器,否則范圍last的迭代器。
//equality (1)
template <class ForwardIterator>
ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last);
//predicate (2)
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last,
BinaryPredicate pred);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::adjacent_find
#include <vector> // std::vector
bool myfunction (int i, int j) {
return (i==j);
}
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';
//using predicate comparison:
it = std::adjacent_find (++it, myvector.end(), myfunction);//從上一個(gè)已經(jīng)找到的地方開始
if (it!=myvector.end())
std::cout << "the second pair of repeated elements are: " << *it << '\n';
return 0;
}
輸出:
the first pair of repeated elements are: 30
the second pair of repeated elements are: 10
(11)count
在range [first,last)中,計(jì)算與val相同的元素個(gè)數(shù)。
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& val);
代碼示例:
#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,20}; // 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;
}
輸出:
10 appears 3 times.
20 appears 3 times.
(12)count_if
在range [first,last)中,計(jì)算讓pred為真的元素個(gè)數(shù)。
template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
代碼示例:
#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); // myvector: 1 2 3 4 5 6 7 8 9
int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "myvector contains " << mycount << " odd values.\n";
return 0;
}
輸出:
myvector contains 5 odd values.
(13)mismatch
找出兩個(gè)序列不匹配的開始點(diǎn),或者找出兩個(gè)序列不滿足條件pred的開始點(diǎn)。
模板1:first2與range [first1,last1) 范圍內(nèi)的元素對比,返回第一個(gè)都不匹配的迭代器組pair(first1, first2)。
模板2:first2與range [first1,last1) 范圍內(nèi)的元素對比,返回第一個(gè)不滿足條件pred的迭代器組pair(first1, first2)。
//equality (1)
template <class InputIterator1, class InputIterator2>
pair<InputIterator1, InputIterator2>
mismatch (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2);
//predicate (2)
template <class InputIterator1, class InputIterator2, class BinaryPredicate>
pair<InputIterator1, InputIterator2>
mismatch (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, BinaryPredicate pred);
代碼舉例:
#include <iostream> // std::cout
#include <algorithm> // std::mismatch
#include <vector> // std::vector
#include <utility> // std::pair
bool mypredicate (int i, int j) {
return (i==j);
}
int main () {
std::vector<int> myvector;
for (int i=1; i<6; i++) myvector.push_back (i*10); // myvector: 10 20 30 40 50
int myints[] = {10,20,80,320,1024}; // myints: 10 20 80 320 1024
std::pair<std::vector<int>::iterator,int*> mypair;
// using default 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;
}
輸出:
First mismatching elements: 30 and 80
Second mismatching elements: 40 and 320
(14)equal
判斷兩個(gè)序列是否相等,或者滿足條件pred。
如果兩個(gè)序列都相等,或者都滿足條件pred,則返回true。
//equality (1)
template <class InputIterator1, class InputIterator2>
bool equal (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2);
//predicate (2)
template <class InputIterator1, class InputIterator2, class BinaryPredicate>
bool equal (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, BinaryPredicate pred);
代碼舉例:
#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}; // myints: 20 40 60 80 100
std::vector<int>myvector (myints,myints+5); // myvector: 20 40 60 80 100
// 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; // myvector: 20 40 60 81 100
// using predicate comparison:
if ( std::equal (myvector.begin(), myvector.end(), myints, mypredicate) )
std::cout << "The contents of both sequences are equal.\n";
else
std::cout << "The contents of both sequences differ.\n";
return 0;
}
輸出:
The contents of both sequences are equal.
The contents of both sequences differ.
(15)is_permutation
permutation的意思是排列,組合的意思。也就是判斷兩個(gè)序列是不是只是重新組合了。
//equality (1)
template <class ForwardIterator1, class ForwardIterator2>
bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2);
//predicate (2)
template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
bool is_permutation (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, BinaryPredicate pred);
代碼示例:
#include <iostream> // std::cout
#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;
}
輸出:
foo and bar contain the same elements.
(16)search
在 range [first1,last1)中尋找[first2,last2)子序列,找到則返回第一個(gè)相等或滿足條件的迭代器,否則范圍last1迭代器。
//equality (1)
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2);
//predicate (2)
template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2,
BinaryPredicate pred);
代碼示例:
#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;
// set some values: 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;
}
輸出:
needle1 found at position 3
needle2 not found
(17)search_n
在 range [first,last)序列中,找出和val相等的個(gè)數(shù),或者滿足條件的pred的個(gè)數(shù),找到則返回第一個(gè)滿足條件的迭代器(指向最后一個(gè)滿足計(jì)數(shù)的迭代器),否則返回last迭代器。
//equality (1)
template <class ForwardIterator, class Size, class T>
ForwardIterator search_n (ForwardIterator first, ForwardIterator last,
Size count, const T& val);
//predicate (2)
template <class ForwardIterator, class Size, class T, class BinaryPredicate>
ForwardIterator search_n ( ForwardIterator first, ForwardIterator last,
Size count, const T& val, BinaryPredicate pred );
2. 修改內(nèi)容的序列操作
(1)copy
復(fù)制range [first,last)的元素到result迭代器開始的序列中。result的范圍不應(yīng)該和[first,last)重疊。
template <class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
代碼舉例:
#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;
}
輸出:
myvector contains: 10 20 30 40 50 60 70
(2)copy_n
復(fù)制從first開始的n個(gè)元素,到result中。
template <class InputIterator, class Size, class OutputIterator> OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);
(3)copy_if
復(fù)制range [first,last)中滿足條件pred的元素,到result中。
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);
(4)copy_backward
和copy類似,只不過copy_backward是從后面開始復(fù)制。
和copy一樣,不允許重疊。
template <class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 copy_backward (BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::copy_backward
#include <vector> // std::vector
int main () {
std::vector<int> myvector;
// set some values:
for (int i=1; i<=5; i++)
myvector.push_back(i*10); // myvector: 10 20 30 40 50
myvector.resize(myvector.size()+3); // allocate space for 3 more elements
std::copy_backward ( myvector.begin(), myvector.begin()+5, 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;
}
輸出:
myvector contains: 10 20 30 10 20 30 40 50
(5)move
從[first,last)的元素移動(dòng)到result中,原來的元素狀態(tài)是有效的,但是元素的值不確定。
move移動(dòng)時(shí)候,不應(yīng)該有重疊。
template <class InputIterator, class OutputIterator> OutputIterator move (InputIterator first, InputIterator last, OutputIterator result);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::move (ranges)
#include <utility> // std::move (objects)
#include <vector> // std::vector
#include <string> // std::string
int main () {
std::vector<std::string> foo = {"air","water","fire","earth"};
std::vector<std::string> bar (4);
// moving ranges:
std::cout << "Moving ranges...\n";
std::move ( foo.begin(), foo.begin()+4, 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 container:
std::cout << "Moving container...\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;
}
輸出:
Moving ranges...
foo contains 4 elements: (each in an unspecified but valid state)
bar contains 4 elements: [air] [water] [fire] [earth]
Moving container...
foo contains 4 elements: [air] [water] [fire] [earth]
bar is in an unspecified but valid state
(6)move_backward
從range [first,last)中移動(dòng)數(shù)據(jù)到result中,不過result是末尾。類似于copy_backward。
move_backward移動(dòng)的時(shí)候,不應(yīng)該有重疊。下面的示例沒有重疊。
template <class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 move_backward (BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::move_backward
#include <string> // std::string
int main () {
std::string elems[10] = {"air","water","fire","earth"};
// insert new element at the beginning:
std::move_backward (elems,elems+4,elems+5);
elems[0]="ether";
std::cout << "elems contains:";
for (int i=0; i<10; ++i)
std::cout << " [" << elems[i] << "]";
std::cout << '\n';
return 0;
}
輸出:
elems contains: [ether] [air] [water] [fire] [earth] [] [] [] [] []
(7)swap
C++11已經(jīng)把該函數(shù)移到<utility>頭文件中,已經(jīng)不在<algorithm>中。
模板1:不修改地址,只交換值。
模板2:交換序列值的內(nèi)容和大小。
交換兩個(gè)元素的值,相應(yīng)地址也會(huì)交換。
//non-array (1) template <class T> void swap (T& a, T& b) noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value); //array (2) template <class T, size_t N> void swap(T (&a)[N], T (&b)[N]) noexcept (noexcept(swap(*a,*b)));
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::swap
#include <vector> // std::vector
int main () {
int x=10, y=20; // x:10 y:20
std::cout<<"x add: "<<&x << "y add: "<< &y<<std::endl;
std::swap(x,y); // x:20 y:10
std::cout<<"x add: "<<&x << "y add: "<< &y<<std::endl;
//x:20 ,y: 10
std::vector<int> foo (4,x), bar (6,y); // foo:4x20 bar:6x10
std::swap(foo,bar); // foo:6x10 bar:4x20
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;
}
輸出:
x add: 0x7ffc1528b7e8y add: 0x7ffc1528b7ec
x add: 0x7ffc1528b7e8y add: 0x7ffc1528b7ec
foo contains: 10 10 10 10 10 10
bar contains: 20 20 20 20
(8)swap_ranges
只交換一部分?jǐn)?shù)據(jù),從range [first1,last1) 對應(yīng)位置,交換first2開始的值。
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::swap_ranges
#include <vector> // std::vector
int main () {
std::vector<int> foo (5,10); // foo: 10 10 10 10 10
std::vector<int> bar (5,33); // bar: 33 33 33 33 33
std::swap_ranges(foo.begin()+1, foo.end()-1, bar.begin());
// print out results of swap:
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;
}
輸出:
foo contains: 10 33 33 33 10
bar contains: 10 10 10 33 33
(9)iter_swap
只交換兩個(gè)序列中,兩個(gè)迭代器所指向的一個(gè)值。
template <class ForwardIterator1, class ForwardIterator2> void iter_swap (ForwardIterator1 a, ForwardIterator2 b);
代碼示例:
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+3,myvector.begin()+2); // myints: 99 20 30 [99] 50
// myvector: 10 99 [40] 99
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
(10)transform
模板1:對 range [first1,last1)都執(zhí)行op操作,然后復(fù)制給result。range [first1,last1)中的元素不會(huì)改變。
模板2:range [first1,last1)中的每個(gè)元素都和first2開始的元素,依次執(zhí)行binary_op操作,然后復(fù)制給result。
//unary operation(1)
template <class InputIterator, class OutputIterator, class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);
//binary operation(2)
template <class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
代碼示例:
#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 values:
for (int i=1; i<6; i++)
foo.push_back (i*10); // foo: 10 20 30 40 50
bar.resize(foo.size()); // allocate space
std::transform (foo.begin(), foo.end(), bar.begin(), op_increase);
// bar: 11 21 31 41 51
// std::plus adds together its two arguments:
std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());
// foo: 21 41 61 81 101
std::cout << "foo contains:";
for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
(11)replace
對 range [first,last) 中所有的old_value元素,使用new_value替換。
template <class ForwardIterator, class T>
void replace (ForwardIterator first, ForwardIterator last,
const T& old_value, const T& new_value);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::replace
#include <vector> // std::vector
int main () {
int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
std::vector<int> myvector (myints, myints+8); // 10 20 30 30 20 10 10 20
std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
myvector contains: 10 99 30 30 99 10 10 99
(12)replace_if
替換所有使得pred為真的元素。
template <class ForwardIterator, class UnaryPredicate, class T>
void replace_if (ForwardIterator first, ForwardIterator last,
UnaryPredicate pred, const T& new_value );
代碼示例:
#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;
// set some values:
for (int i=1; i<10; i++) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
std::replace_if (myvector.begin(), myvector.end(), IsOdd, 0); // 0 2 0 4 0 6 0 8 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;
}
(13)replace_copy
從range [first,last) 拷貝元素到以result為起始的迭代器中, 并修改old_value為new_value。原來的序列元素保持不變。
template <class InputIterator, class OutputIterator, class T>
OutputIterator replace_copy (InputIterator first, InputIterator last,
OutputIterator result,
const T& old_value, const T& new_value);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::replace_copy
#include <vector> // std::vector
int main () {
int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
std::vector<int> myvector (8);
std::replace_copy (myints, myints+8, myvector.begin(), 20, 99);
for(auto x:myints)
std::cout<<x<<", ";
std::cout<<std::endl;
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
10, 20, 30, 30, 20, 10, 10, 20,
myvector contains: 10 99 30 30 99 10 10 99
(14)replace_copy_if
從range [first,last) 拷貝元素到以result為起始的迭代器中, 如果滿足pred為真,元素修改為new_value。原來的序列元素保持不變。
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);
代碼示例:
#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;
// set some values:
for (int i=1; i<10; i++) foo.push_back(i); // 1 2 3 4 5 6 7 8 9
bar.resize(foo.size()); // allocate space
std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0);
// 0 2 0 4 0 6 0 8 0,只修改奇數(shù)
std::cout << "bar contains:";
for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
(15)fill
使用val填充 range [first,last)。
template <class ForwardIterator, class T> void fill (ForwardIterator first, ForwardIterator last, const T& val);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::fill
#include <vector> // std::vector
int main () {
std::vector<int> myvector (8); // myvector: 0 0 0 0 0 0 0 0
std::fill (myvector.begin(),myvector.begin()+4,5); // myvector: 5 5 5 5 0 0 0 0
std::fill (myvector.begin()+3,myvector.end()-2,8); // myvector: 5 5 5 8 8 8 0 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;
}
輸出:
myvector contains: 5 5 5 8 8 8 0 0
(16)fill_n
填充n個(gè)val元素到以first開始的序列
template <class OutputIterator, class Size, class T> OutputIterator fill_n (OutputIterator first, Size n, const T& val);
(17)generate
以gen規(guī)則生成的元素,依次復(fù)制給 range [first,last)。
template <class ForwardIterator, class Generator> void generate (ForwardIterator first, ForwardIterator last, Generator gen);
(18)generate_n
以gen規(guī)則生成的元素,依次復(fù)制給以first開始的n個(gè)元素。
template <class OutputIterator, class Size, class Generator> OutputIterator generate_n (OutputIterator first, Size n, Generator gen);
(19)remove
刪除 range [first,last)中和val相同的元素,并返回新序列的end迭代器。
template <class ForwardIterator, class T> ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::remove
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove (pbegin, pend, 20); // 10 30 30 10 10 ? ? ?
// ^ ^
std::cout << "range contains:";
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
return 0;
}
輸出:
range contains: 10 30 30 10 10
(20)remove_if
刪除 range [first,last)中滿足pred條件的元素,并返回新序列的end迭代器。
template <class ForwardIterator, class UnaryPredicate>
ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,
UnaryPredicate pred);
(21)remove_copy
除了和val相同的元素,復(fù)制range [first,last)中的元素到result開始的元素中。原來的序列保持不變。
template <class InputIterator, class OutputIterator, class T>
OutputIterator remove_copy (InputIterator first, InputIterator last,
OutputIterator result, const T& val);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::remove_copy
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
std::vector<int> myvector (8);
std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 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;
}
(22)remove_copy_if
除了使得pred為真的元素,復(fù)制range [first,last)中的元素到result開始的元素中。原來的序列保持不變。
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator remove_copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);
(23)unique
在range[first,last)中,如果遇到連續(xù)的相同元素,只保留第一個(gè)。并返回處理完畢之后的end迭代器。
刪除的地方補(bǔ)0,可以用resize去掉。
模板1:默認(rèn)相等
模板2:自定義pred相等規(guī)則
//equality (1)
template <class ForwardIterator>
ForwardIterator unique (ForwardIterator first, ForwardIterator last);
//predicate (2)
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique (ForwardIterator first, ForwardIterator last,
BinaryPredicate pred);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::unique, std::distance
#include <vector> // std::vector
bool myfunction (int i, int j) {
return (i==j);
}
int main () {
int myints[] = {10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10
std::vector<int> myvector (myints,myints+9);
// using default comparison:
std::vector<int>::iterator it;
it = std::unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 ? ? ? ?,指向第一個(gè)?
myvector.resize( std::distance(myvector.begin(),it) ); // 10 20 30 20 10
// using predicate comparison:
std::unique (myvector.begin(), myvector.end(), myfunction); // (no changes)
// print out content:
std::cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
myvector contains: 10 20 30 20 10
(24)unique_copy
復(fù)制unique元素到result中,原來的元素保持不變。
//equality (1)
template <class InputIterator, class OutputIterator>
OutputIterator unique_copy (InputIterator first, InputIterator last,
OutputIterator result);
//predicate (2)
template <class InputIterator, class OutputIterator, class BinaryPredicate>
OutputIterator unique_copy (InputIterator first, InputIterator last,
OutputIterator result, BinaryPredicate pred);
(25)reverse
反轉(zhuǎn)序列
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::reverse
#include <vector> // std::vector
int main () {
std::vector<int> myvector;
// set some values:
for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
std::reverse(myvector.begin(),myvector.end()); // 9 8 7 6 5 4 3 2 1
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
(26)reverse_copy
復(fù)制反轉(zhuǎn)的序列,原來的序列保持不變。
template <class BidirectionalIterator, class OutputIterator>
OutputIterator reverse_copy (BidirectionalIterator first,
BidirectionalIterator last, OutputIterator result);
(27)rotate
以middle為圓點(diǎn),調(diào)換左右序列,其中middle迭代器指向的元素為第一個(gè)元素。。
template <class ForwardIterator>
ForwardIterator rotate (ForwardIterator first, ForwardIterator middle,
ForwardIterator last);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::rotate
#include <vector> // std::vector
int main () {
std::vector<int> myvector;
// set some values:
for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
std::rotate(myvector.begin(),myvector.begin()+3,myvector.end());
// 4 5 6 7 8 9 1 2 3
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
myvector contains: 4 5 6 7 8 9 1 2 3
(28)rotate_copy
復(fù)制旋轉(zhuǎn)過的元素到result中,但是原來的序列保持不變。這一點(diǎn)像reverse_copy。
template <class ForwardIterator, class OutputIterator>
OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle,
ForwardIterator last, OutputIterator result);
(29)random_shuffle
shuffle意思是洗牌。
gen是自己定義的隨機(jī)種子。
//generator by default (1)
template <class RandomAccessIterator>
void random_shuffle (RandomAccessIterator first, RandomAccessIterator last);
//specific generator (2)
template <class RandomAccessIterator, class RandomNumberGenerator>
void random_shuffle (RandomAccessIterator first, RandomAccessIterator last,
RandomNumberGenerator&& gen);
(30)shuffle
也是重新洗牌。
template <class RandomAccessIterator, class URNG> void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);
3. 劃分操作(Partitions)
(1)is_partitioned
(2)partition
(3)stable_partition
(4)partition_copy
(5)partition_point
4. 排序操作(sorting)
(1)sort
默認(rèn)排序:升序
模板2:根據(jù)comp返回true的狀態(tài)排序
不保證相同元素,保持原來的排序方法。如果需要保持原來的順序,可以使用stable_sort。
//default (1) template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); //custom (2) template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
代碼示例:
#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
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)普通函數(shù)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)函數(shù)對象
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
(2)stable_sort
和sort一樣,只不過相同元素保持原來的排序。
(3)partial_sort
middle之前的元素,都是小于或等于middle,而且經(jīng)過排序。middle之后的元素沒有指定順序。
//default (1)
template <class RandomAccessIterator>
void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,
RandomAccessIterator last);
//custom (2)
template <class RandomAccessIterator, class Compare>
void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,
RandomAccessIterator last, Compare comp);
(4)partial_sort_copy
從range [first,last),復(fù)制最小的一部分元素,到 [result_first,result_last),并排序。原來的序列保持不變。
[first,last)小于[result_first,result_last)則只截取最小的一部分,否則全部排序并復(fù)制。
模板1:默認(rèn)升排序
模板2:自定義comp規(guī)則。
//default (1)
template <class InputIterator, class RandomAccessIterator>
RandomAccessIterator
partial_sort_copy (InputIterator first,InputIterator last,
RandomAccessIterator result_first,
RandomAccessIterator result_last);
//custom (2)
template <class InputIterator, class RandomAccessIterator, class Compare>
RandomAccessIterator
partial_sort_copy (InputIterator first,InputIterator last,
RandomAccessIterator result_first,
RandomAccessIterator result_last, Compare comp);
(5)is_sorted
判斷序列是否排序。
模板1:默認(rèn)排序
模板2:自定義comp規(guī)則。
//default (1) template <class ForwardIterator> bool is_sorted (ForwardIterator first, ForwardIterator last); //custom (2) template <class ForwardIterator, class Compare> bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);
(6)is_sorted_until
模板1:返回第一個(gè)不滿足默認(rèn)升排序的迭代器
模板2:返回第一個(gè)不滿足自定義comp規(guī)則的迭代器。
//default (1)
template <class ForwardIterator>
ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last);
//custom (2)
template <class ForwardIterator, class Compare>
ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last,
Compare comp);
(7)nth_element
重新排列range [first,last)元素。nth左邊的元素是小的,右邊的元素是大的。
模板1:默認(rèn)排序。
模板2:comp規(guī)則
//default (1)
template <class RandomAccessIterator>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last);
//custom (2)
template <class RandomAccessIterator, class Compare>
void nth_element (RandomAccessIterator first, RandomAccessIterator nth,
RandomAccessIterator last, Compare comp);
代碼示例:
#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;
// set some values:`在這里插入代碼片`
for (int i=1; i<10; i++) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
std::random_shuffle (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';
// using default comparison (operator <):
//以myvector.begin()+5為中心
std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end());
// using function as comp
std::nth_element (myvector.begin(), myvector.begin()+5, myvector.end(),myfunction);
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
myvector contains: 5 4 8 9 1 6 3 2 7
myvector contains: 5 2 3 1 4 6 7 8 9
5. 二分查找操作(Binary search)
二分查找需要所有元素經(jīng)過排序。
(1)lower_bound
模板1:返回第一個(gè)不小于val元素指向的迭代器。
模板2:依據(jù)comp規(guī)則,返回第一個(gè)不小于val的元素的迭代器。
模板1內(nèi)所有元素都是通過"<"排序,模板2都是通過comp排序。
//default (1)
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
const T& val);
//custom (2)
template <class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // 指向第一個(gè)20
up= std::upper_bound (v.begin(), v.end(), 20); // 指向20后面第一個(gè)大于20的元素
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
輸出:
lower_bound at position 3
upper_bound at position 6
(2)upper_bound
模板1:返回第一個(gè)大于val元素指向的迭代器
模板2:依據(jù)comp規(guī)則,返回第一個(gè)大于val的元素的迭代器。
模板1內(nèi)所有元素都是通過"<"排序,模板2都是通過comp排序。
//default (1)
template <class ForwardIterator, class T>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
const T& val);
//custom (2)
template <class ForwardIterator, class T, class Compare>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
(3)equal_range
模板1:返回 range [first,last)內(nèi),所有等于val元素的邊界對pair(low, upper)。
模板2:返回 range [first,last)內(nèi),所有等于val元素的邊界對pair(low, upper)。
模板1內(nèi)所有元素都是通過"<"排序,模板2都是通過comp排序。
//default (1)
template <class ForwardIterator, class T>
pair<ForwardIterator,ForwardIterator>
equal_range (ForwardIterator first, ForwardIterator last, const T& val);
//custom (2)
template <class ForwardIterator, class T, class Compare>
pair<ForwardIterator,ForwardIterator>
equal_range (ForwardIterator first, ForwardIterator last, const T& val,
Compare comp);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::equal_range, std::sort
#include <vector> // std::vector
bool mygreater (int i,int j) { return (i>j); }
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds;
// using default comparison:
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
bounds=std::equal_range (v.begin(), v.end(), 20);// ^ ^
// using "mygreater" as comp:
std::sort (v.begin(), v.end(), mygreater); // 30 30 20 20 20 10 10 10
bounds=std::equal_range (v.begin(), v.end(), 20, mygreater); // ^ ^
std::cout << "bounds at positions " << (bounds.first - v.begin());
std::cout << " and " << (bounds.second - v.begin()) << '\n';
return 0;
}
輸出:
bounds at positions 2 and 5
(4)binary_search
range [first,last)中的元素至少有一個(gè)等于val,則返回true,否則返回false。
序列應(yīng)該按照默認(rèn)升序或者comp規(guī)則排序。
//default (1)
template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val);
//custom (2)
template <class ForwardIterator, class T, class Compare>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
6. 集合(Merge)
(1)merge
(2)inplace_merge
(3)includes
(4)set_union
(5)set_intersection
(6)set_difference
(7)set_symmetric_difference
7. 堆操作
(1)push_heap
(2)pop_heap
(3)make_heap
(4)sort_heap
(5)is_heap
(6)is_heap_until
8. 最小最大值操作
(1)min
返回兩個(gè)元素的最小的一個(gè)。
模板1:內(nèi)置數(shù)據(jù)類型
模板2和模板3:自己定義comp
模板3可以有多個(gè)元素。
//default (1) template <class T> constexpr const T& min (const T& a, const T& b); //custom (2) template <class T, class Compare> constexpr const T& min (const T& a, const T& b, Compare comp); //initializer list (3) template <class T> constexpr T min (initializer_list<T> il); template <class T, class Compare> constexpr T min (initializer_list<T> il, Compare comp);
代碼示例:
#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';
std::cout<<std::min({1,2,4,5,6,7})<<std::endl;
return 0;
}
輸出:
min(1,2)==1
min(2,1)==1
min('a','z')==a
min(3.14,2.72)==2.72
1
(2)max
同min
(3)minmax
返回make_pair(a,b),a為最小值,b為最大值。
模板3可以有多個(gè)元素。
//default (1) template <class T> constexpr pair <const T&,const T&> minmax (const T& a, const T& b); //custom (2) template <class T, class Compare> constexpr pair <const T&,const T&> minmax (const T& a, const T& b, Compare comp); //initializer list (3) template <class T> constexpr pair<T,T> minmax (initializer_list<T> il); template <class T, class Compare> constexpr pair<T,T> minmax (initializer_list<T> il, Compare comp);
(4)min_element
模板1:返回最小元素的迭代器
模板2:根據(jù)comp的小于號定義規(guī)則(一定要升序),不然結(jié)果相反。
//default (1)
template <class ForwardIterator>
ForwardIterator min_element (ForwardIterator first, ForwardIterator last);
//custom (2)
template <class ForwardIterator, class Compare>
ForwardIterator min_element (ForwardIterator first, ForwardIterator last,
Compare comp);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::min_element, std::max_element
bool myfn(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,4,9};
// using default comparison:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7) << '\n';
// using function myfn as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myfn) << '\n';
// using object myobj as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myobj) << '\n';
return 0;
}
輸出:
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9
(5)max_element
同min_element
(6)minmax_element
同minmax規(guī)則,不過返回的是迭代器。
9. 其他
(1)lexicographical_compare
類似于字符串比較大小,這里可以自定義數(shù)據(jù)類型比較。[first1,last1) 的元素小于[first2,last2),則返回true。
模板1:默認(rèn)小于
模板2:自定義comp判斷。
//default (1)
template <class InputIterator1, class InputIterator2>
bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2);
//custom (2)
template <class InputIterator1, class InputIterator2, class Compare>
bool lexicographical_compare (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
Compare comp);
代碼示例:
#include <iostream> // std::cout, std::boolalpha
#include <algorithm> // std::lexicographical_compare
#include <cctype> // std::tolower
// a case-insensitive comparison function:
bool mycomp (char c1, char c2)
{ return std::tolower(c1)<std::tolower(c2); }//自定義,轉(zhuǎn)換成小寫比較
int main () {
char foo[]="Apple";
char bar[]="apartment";
std::cout << std::boolalpha;
std::cout << "Comparing foo and bar lexicographically (foo<bar):\n";
std::cout << "Using default comparison (operator<): ";
std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9);
std::cout << '\n';
std::cout << "Using mycomp as comparison object: ";
std::cout << std::lexicographical_compare(foo,foo+5,bar,bar+9,mycomp);
std::cout << '\n';
return 0;
}
輸出:
Comparing foo and bar lexicographically (foo<bar):
Using default comparison (operator<): true
Using mycomp as comparison object: false
(2)next_permutation
- permutation表示排序。
- 獲取比現(xiàn)在的數(shù)據(jù)排列大的一組數(shù)據(jù),并獲取新的排列。比如比1,2,3大的下一次排列為1,3,2.
- 如果已經(jīng)是最大排序,那么它先獲取下一次的排序,比如321下一次的排序?yàn)?23,并返回false。
模板1:默認(rèn)排序
模板2:自定義comp排序
//default (1)
template <class BidirectionalIterator>
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last);
//custom (2)
template <class BidirectionalIterator, class Compare>
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last, Compare comp);
代碼示例:
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort
int main () {
int myints[] = {1,2,3};
std::sort (myints,myints+3);
std::cout << "The 3! possible permutations with 3 elements:\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;
}
輸出結(jié)果:
The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3
(3)prev_permutation
用法同next_permutation,只不過它獲取的是下一次的較大值。
參考:http://www.cplusplus.com/reference/algorithm/
到此這篇關(guān)于C++頭文件algorithm中的函數(shù)功能詳解的文章就介紹到這了,更多相關(guān)C++頭文件algorithm函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 簡單談?wù)凜++ 頭文件系列之(algorithm)
- 詳解C++中的萬能頭文件
- 關(guān)于VS2022不能使用<bits/stdc++.h>的解決方案(萬能頭文件)
- C++ Boost Algorithm算法超詳細(xì)精講
- C++實(shí)現(xiàn)分水嶺算法(Watershed Algorithm)
- C++詳細(xì)講解常用math函數(shù)的用法
- C++常用字符串函數(shù)大全(2)
- 詳解C++字符串常用操作函數(shù)(查找、插入、截取、刪除等)
- c++中的string常用函數(shù)用法總結(jié)
- C++常用函數(shù)總結(jié)(algorithm 頭文件)
相關(guān)文章
解決Devc++運(yùn)行窗口中文亂碼的實(shí)現(xiàn)步驟
本文主要介紹了如何解決Devc++運(yùn)行窗口中文亂碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
C++實(shí)現(xiàn)LeetCode(186.翻轉(zhuǎn)字符串中的單詞之二)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(186.翻轉(zhuǎn)字符串中的單詞之二),本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
一文詳解如何實(shí)現(xiàn)QT的多語言切換(靜態(tài)+動(dòng)態(tài))
這篇文章主要給大家介紹了關(guān)于如何實(shí)現(xiàn)QT的多語言切換(靜態(tài)+動(dòng)態(tài))的相關(guān)資料,Qt是一款跨平臺(tái)的C++應(yīng)用程序開發(fā)框架,提供了一套豐富的工具和類庫來簡化應(yīng)用程序開發(fā),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06

