打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
泛型算法使用整理
accumulate用于容器元素的“累运算”,累加,累乘,等等,默认累加。
accumulate (coll.begin(), coll.end()) ;  
accumulate (coll.begin(), coll.end(),    // range
                        1,                           // initial value
                        multiplies<int>())           // operation


adjacent_difference创建一个新序列,用于相邻元素的运算,默认为差值。
adjacent_difference (coll.begin(), coll.end(),         // source
                        ostream_iterator<int>(cout," ")); // dest.

   adjacent_difference (coll.begin(), coll.end(),         // source
                        iresult.begin(), // dest.
                        plus<int>());                     // operation


adjacent_find 用于容器元素相邻元素的查找,默认为相等。
pos = adjacent_find (coll.begin(), coll.end());

bool doubled (int elem1, int elem2)
{
   return elem1 * 2 == elem2;
}
pos = adjacent_find (coll.begin(), coll.end(),   // range
                        doubled);                   // criterion


一些常用的运算函数对象
plus<int>()   加
multiplies<int>()   乘
times<int>() 乘
greater<int>() 大于
modulus<int>() 取模
less<int>()   小于
negate<int>() 符号取反


binary_search查找某个元素是否存在,返回布尔值。
binary_search(coll.begin(), coll.end(), 5)



copy( InputIterator first1, InputIterator last, OutputIterator first2 );
copy()把由[first,last)标记的序列中的元素 拷贝到由 first2 标记为开始的地方

copy (coll1.begin(), coll1.end(),         // source range
          back_inserter(coll2));              // destination range,这种方式一般是coll2只是被声明,还没有元素。
copy (coll2.begin(), coll2.end(),         // source range
          ostream_iterator<int>(cout," "));   // destination range
copy (coll1.rbegin(), coll1.rend(),       // source range
          coll2.begin());                     // destination range,这种方式必须保证coll2已经分配了足够的空间。
copy (istream_iterator<string>(cin),         // beginning of source
          istream_iterator<string>(),            // end of source 缺省构造函数,表示结尾。
          ostream_iterator<string>(cout,"\n")); // destination 从cin读入,按行输出到cout


count查找数量,count_if满足某个条件函数的元素数量
num = count (coll.begin(), coll.end(),       // range
                 4);   
bool isEven (int elem)
{
    return elem % 2 == 0;
}
num = count_if (coll.begin(), coll.end(),    // range
                    isEven);   


fill()将 value 的拷贝赋给[first,last)范围内的所有元素
f i l l _ n ( )把 value 的拷贝赋给[first,first+count)范围内的 count 个元素
// insert "hello" nine times
    fill_n(back_inserter(coll),       // beginning of destination
           9,                         // count
           "hello");                  // new value
// overwrite all elements with "again"
    fill(coll.begin(), coll.end(),    // destination
         "again");                    // new value


find()、find_if()
// find first element with value 4
    list<int>::iterator pos1;
    pos1 = find (coll.begin(), coll.end(),    // range
                 4);                          // value
// find first element greater than 3
    pos = find_if (coll.begin(), coll.end(),    // range
                   bind2nd(greater<int>(),3)); // criterion

find_end()
在由[first,last)标记的序列中查找 由 iterator 对[first2,last2)标记的第二个序列的最后一次出现.
    // search last occurrence of subcoll in coll
    deque<int>::iterator pos;
    pos = find_end (coll.begin(), coll.end(),         // range
                    subcoll.begin(), subcoll.end()); // subrange


find_first_of()
由[first2,last2)标记的序列包含了一组元素的集合 find_first_of()将在由[first1,last1)标记的序列中搜索这些元素。注意与find_end不同的一点是这里是搜元素,而find_end是搜整个匹配。
INSERT_ELEMENTS(coll,1,11);
    INSERT_ELEMENTS(searchcoll,3,5);

// search first occurrence of an element of searchcoll in coll
    vector<int>::iterator pos;
    pos = find_first_of (coll.begin(), coll.end(),     // range
                         searchcoll.begin(),   // beginning of search set
                         searchcoll.end());    // end of search set

// search last occurrence of an element of searchcoll in coll
    vector<int>::reverse_iterator rpos;    // 用了反向iterator
    rpos = find_first_of (coll.rbegin(), coll.rend(), // range
                          searchcoll.begin(), // beginning of search set
                          searchcoll.end());   // end of search set



for_each()依次对[first,last)范围内的所有元素应用函数 func func 不能对元素执行写操作
void print (int elem)
{
    cout << elem << ' ';
}
// call print() for each element
    for_each (coll.begin(), coll.end(), // range
              print);                    // operation 函数指针

#include "algostuff.hpp"
using namespace std;

// function object that adds the value with which it is initialized
template <class T>
class AddValue {
private:
    T theValue;    // value to add
public:
    // constructor initializes the value to add
    AddValue (const T& v) : theValue(v) {
    }

    // the function call for the element adds the value
    void operator() (T& elem) const {
        elem += theValue;
    }
};
函数对象必须实现()操作符。
int main()
{
    vector<int> coll;

    INSERT_ELEMENTS(coll,1,9);

    // add ten to each element
    for_each (coll.begin(), coll.end(),       // range
              AddValue<int>(10));             // operation 函数对象实例
    PRINT_ELEMENTS(coll);

    // add value of first element to each element
    for_each (coll.begin(), coll.end(),       // range
              AddValue<int>(*coll.begin())); // operation
    PRINT_ELEMENTS(coll);
}



generate( ForwardIterator first,
ForwardIterator last, Generator gen );
g e n e r a t e ( )通过对 gen的连续调用 来填充一个序列的[first,last)范围 gen可以是函数对象或函数指针
generate_n( OutputIterator first, Size n, Generator gen );
generate_n()通过对 gen的 n 次连续调用 来填充一个序列中从 first 开始的n个元素 gen可以是函数对象函数指针
list<int> coll;

    // insert five random numbers
    generate_n (back_inserter(coll),      // beginning of destination range
                5,                        // count
                rand);                    // new value generator
    PRINT_ELEMENTS(coll);

// overwrite with five new random numbers
    generate (coll.begin(), coll.end(),   // destination range
              rand);                      // new value generator



includes( )判断[first1,last1)的每一个元素是否被包含在序列[first2,last2)中



void
iter_swap ( ForwardIterator1 a, ForwardIterator2 b );
    i t e r _ s w a p ( )交换由两个 ForwardIterator a 和 b 所指向的元素中的值

template< class Type >
void
swap ( Type &ob1, Type &ob2 );
s w a p ( )交换存贮在对象 ob1 和 ob2 中的值
swap( vec[iy], vec[ix] );

swap_range()将[first,last)标记的元素值与 从 first2 开始 相同个数 的元素值进行交换,这两个序列可以是同一容器中不相连的序列,也可以位于两个独立的容器中。
pos = swap_ranges (coll1.begin(), coll1.end(), // first range
                       coll2.begin());              // second range



m a x ( )返回 aval 和 bval 两个元素中较大的一个。
max_element()返回一个iterator 指向[first,last)序列中值为最大的元素
m i n ( )返回 aval 和 bval 两个元素中较小的一个。
min_element()返回一个 iterator 指向[first,last)序列中值为最小的元素


r e m o v e ( )删除在[first,last)范围内的所有value 实例, remove()以及 remove_if()并不真正地 把匹配到的元素从容器中清除 (即容器的大小保留不变), 而是每个不匹配的元素依次被赋值给从 first 开始的下一个空闲位置上,返问的ForwardIterator 标记了新的元素范围的下一个位置。例如,考虑序列{0,1,0,2,0,3,0,4} 假设我们希望删除所有的 0 ,则结果序列是 {1,2,3,4,0,3,0,4}。 1 被拷贝到第一个位置上, 2 被拷贝到第二个位置上, 3被拷贝到第三个位置上,4 被拷贝到第四个位置上,返回的ForwardIterator 指向第五个位置上的 0。典型的做法是该 iterator 接着被传递给 erase() ,以便删除无效的元素 内置数组不适合于使用 remove() 和 remove_if()算法,因为它们不能很容易地被改变大小,由于这个原因 对于数组而言 remove_copy()和 remove_copy_if()是更受欢迎的算法。
// remove all elements with value 5
pos = remove(coll.begin(), coll.end(),   // range
                 5);                         // value to remove
// erase the ``removed'' elements in the container
coll.erase(pos, coll.end());

// remove all elements less than 4
coll.erase(remove_if(coll.begin(), coll.end(), // range
                         bind2nd(less<int>(),4)),   // remove criterion
               coll.end());

remove_copy()把所有不匹配的元素都拷贝到由 result 指定的容器中,返回的OutputIterator 指向被拷贝的末元素的下一个位置,但原始容器没有被改变。
// print elements without those having the value 3
    remove_copy(coll1.begin(), coll1.end(),       // source
                ostream_iterator<int>(cout," "), // destination    
                3);                               // removed value



replace()将[first,last)范围内的所有 old_value 实例都用 new_value 替代
replace_copy()的行为与 replace()类似 只不过是把新序列拷贝到由result 开始的容器内
replace_if()、replace_copy_if()
// replace all elements with value 6 with 42
    replace (coll.begin(), coll.end(),     // range
             6,                            // old value
             42);                          // new value

// replace all elements with value less than 5 with 0
    replace_if (coll.begin(), coll.end(), // range
                bind2nd(less<int>(),5),    // criterion for replacement
                0);                        // new value

// print all elements with value 5 replaced with 55
    replace_copy(coll.begin(), coll.end(),           // source
                 ostream_iterator<int>(cout," "),    // destination
                 5,                                  // old value
                 55);                                // new value




r e v e r s e ( )对于容器中[first,last)范围内的元素重新按反序排列 例如 已知序列{0,1,1,2,3} ,则反序序列是{3,2,1,1,0}
reverse_copy()
// reverse order of elements
    reverse (coll.begin(), coll.end());

// print all of them in reverse order
    reverse_copy (coll.begin(), coll.end(),           // source
                  ostream_iterator<int>(cout," "));   // destination



r o t a t e ( )把[first,middle)范围内的元素移到容器末尾,由 middle 指向的元素成为容器的第一个元素。例如,已知单词 hissboo 则以元素 b 为轴的旋转将单词变成 boohiss
rotate_copy()
    rotate (coll.begin(),      // beginning of range
            coll.begin() + 1, // new first element
            coll.end());       // end of range

// rotate so that element with value 4 is the beginning
    rotate (coll.begin(),                     // beginning of range
            find(coll.begin(),coll.end(),4), // new first element
            coll.end());                      // end of range



search()
给出了两个范围 ,search()返回一个iterator 指向在[first1,last1)范围内第一次出现子序列[first2,last2]的位置。 如果子序列未出现,则返回 last1。例如,在 mississippi 中 子序列iss 出现两次,则 search()返回一个iterator 指向第一个实例的起始处。缺省情况下 使用等于操作符进行元素的比较,第二个版本允许用户提供一个比较操作。
    pos = search (coll.begin(), coll.end(),         // range
                  subcoll.begin(), subcoll.end()); // subrange

    // loop while subcoll found as subrange of coll
    while (pos != coll.end())
search_n()在[first,last)序列中查找 value 出现 count 次 的子序列



set_difference()构造一个排过序的序列,其中的元素出现在第一个序列中,由[first,last)标记,但是不包含在第二个序列中,由[first2,last2]标记。例如,已失两个序列{0,1,2,3} 和{0,2,4,6} 则差集为{1,3}

set_intersection()构造一个排过序的序列,其中的元素在[first1,last1)和[first2,last2)序列中都存在。例如,已知序列{0,1,2,3}和{0,2,4,6} 则交集为{0,2}。

set_union()构造一个排过序的序列,它包含了[first1,last1)和[first2,last2)这两个范围内的所有元素。例如,已知两个序列{0,1,2,3}和{0,2,4,6},则并集为{0,1,2,3,4,6}。




s o r t ( )利用底层元素的小于操作符 以升序重新排列[first,last)范围内的元素。
// sort elements
sort (coll.begin(), coll.end());

// sorted reverse
sort (coll.begin(), coll.end(),    // range
          greater<int>());             // sorting criterion

bool lessLength (const string& s1, const string& s2)
{
    return s1.length() < s2.length();
}
// sort (according to the length of the strings)
    sort (coll1.begin(), coll1.end(),           // range
          lessLength);                          // criterion
stable_sort()利用底层类型的小于操作符 以升序重新排列[first,last)范围内的元素 并且
保留相等元素之间的顺序关系



t r a n s f o r m ( )的第一个版本将 op 作用在[first,last)范围内的每个元素上,从而产生一个新的序列。例如,已知序列{0,1,1,2,3,5}和函数对象 Double 它使每个元素加倍 那么 结果序列是{0,2,2,4,6,10}
// negate all elements in coll1
    transform (coll1.begin(), coll1.end(),      // source range
               coll1.begin(),                   // destination range
               negate<int>());                  // operation

// transform elements of coll1 into coll2 with ten times their value
    transform (coll1.begin(), coll1.end(),      // source range
               back_inserter(coll2),            // destination range
               bind2nd(multiplies<int>(),10)); // operation

第二个版本将bop 作用在一对元素上,其中一个元素来自序列[first1,last), 另一个来自由first2 开始的序列 最终产生一个新的序列。如果第二个序列包含的元素少于第一个序列,则运行时刻行为是未定义的。例如,已知序列{1,3,5,9}和{2,4,6,8} 以及函数对象 AddAndDouble,它把两个元素相加并将和加倍,则结果序列是{6,14,22,34}
   // square each element
    transform (coll1.begin(), coll1.end(),       // first source range
               coll1.begin(),                    // second source range
               coll1.begin(),                    // destination range
               multiplies<int>());               // operation



unique()对于连续的元素, 如果它们包含相同的值(使用底层类型的等于操作符来判断)或者把它们传给pred的计算结果都为 true,则这些元素被折叠成一个元素。实际上 unique()的行为有些不太直观,类似于 remove()算法。典型的做法是 这个 iterator 被传递给 erase() 以便删除无效的元素,由于内置数组不支持erase()操作,所以unique()不太适合于数组,unique_copy()对数组更为合适一些。
其实就是运用泛型算法时,算法不会去改变原容器的大小,所以remove和unique算法才会有此现象。
pos = unique (coll.begin(), coll.end());

    // print elements
    copy (coll.begin(), pos,                  // source
          ostream_iterator<int>(cout," "));   // destination
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【C++ STL】Set和Multiset
STL 算法集合
Java集合Collection和泛型
Iterator、Iterable接口的使用及详解
C++ 迭代器 基础介绍
标准模板库(STL)使用入门(上)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服