Road C ++ learning --7

  • stack container

    • First, look at what is the stack
    • Last-out, no iteratorsHere Insert Picture Description
  • Common API
    ,Here Insert Picture Description

  • queue container

    • FIFO
    • Here Insert Picture Description
    • Common API
      Here Insert Picture Description
  • list container - two-way circular list

    • It does not support random accessHere Insert Picture DescriptionHere Insert Picture Description
    • reverse the sort list
    • reverse () Reverse list
    • sort () to sort the default small to large order, when required descending order need to add a callback function,
    void mycompare(int v1,int v2)
    {
    return v1>v2;
    }
    L.sort(mycompare);
    
    
    
    
  • set容器 key —value

    • Associative containers inserted automatically sort data according to key, insert interpolated values, parameters can be passed by value ERASE.
    • set to find find (key) not found return s.end ()
    • count (key) to find the number of elements of key key
    • lower_bound () returns the first key> = iterator keyElem element.
    • upper_bound (keyElem) returns the first key> iterator keyElem element.
    • equal_range () Returns the key vessel keyElem equal to the lower limit of two iterators.
  • 对组 pair<string ,int> make_pair()

  • set sorting containers - before inserting the collation must be specified, with the functor set <int, myCompare> s1;

  • class myCompare

  • { public: bool operator()(int v1,int v2) return v1>v2;}

  • Collation must be specified when inserting custom data types.

  • map容器 key value

    • 插入方式 m.insert(pair<int ,int > (1, 10)) m.insert(make_pair(1,10)) m.insert(map<int,int >:: value_type(1,10)) m[4]=41;

Here Insert Picture DescriptionHere Insert Picture DescriptionHere Insert Picture DescriptionHere Insert Picture Description
Commonly used algorithms

  • Overload () operator, similar to the behavior of the function, it is the functor.
  • Here Insert Picture Description
  • Refers predicate ordinary function or overloaded operator () return value is a function of the type bool objects. A predicate is a predicate.
  • lambda anonymous function:{}
  • Built-in functions

    -Here Insert Picture Description
  • adapter

    • Headers #include <functional>
    • Bind2nd
    • Inherited class :: public binary_function <int, int, void> void return type
    • Const qualifier operator ()
    • Inherited negated adapter not1 unary_function <parameter 1, return type>
    • const modified operator
    • Ptr_fun adapter function pointer () function pointer may be adapted as a function of the object
    • Member function adapter mem_fun_ref ()
  • Commonly used algorithms

    • the for_each () can return a value to traverse, the output parameter can be bound
    • transform () Handling need to open up space in advanceHere Insert Picture Description
    • find Find element, find custom data types can find value lookup
    • find_if find elements can find an address lookup conditions
    • adjacent_find find adjacent repeating elements
    • binary_search binary search algorithm
    • Find count_if count the number of elements appear (v.begin (), v, end (). 4)
    • random_shuffle(iterator beg,iterator end) 洗牌
    • reverse () Reverse
    • merge () elements into a container, two containers must be ordered, sequentially consistent
    • sort () to sort
    • Copy and replacement algorithm
    • copy () Copy beg end dest three parameters copy (v.begin (), v.end (), ostream_iterator <int> (cout, "")); header file must iterator
    • Alternatively replace values ​​beg, end, oldvalue, newvalue
    • Alternatively replace_if conditions beg, end, callback, newvalue
    • 1 c2 c1 for swap container vessel 2
    • and accumulate the cumulative calculation container header numeric beg end value Start value
    • fill filled beg end value added element to the vessel filling value
    • Intersection set_intersection beg1 end1 beg2 end2 dest Returns an iterator address of the last element of the target container
    • And set set_union beg1 end1 beg2 end2 dest target container iterator returns the last element of the address
    • Difference set set_difference beg1 end1 beg2 end2 dest target container iterator returns the last element of the address
    • min max

STL algorithms part of the main header file ,, composed. To use the STL algorithm functions must include the header files for numerical algorithm shall contain, in the definition of some of the template class to declare the function object.
STL algorithm roughly divided into four categories:
1, non-variable and sequence algorithm: that is not directly modify the contents of the container it operates an algorithm.
2, the variable sequence algorithm: means can modify the contents of the container on which they operate algorithm.
3, sorting algorithms: an algorithm comprising a set of operation sequences on the sort and merge, and an ordered sequence search algorithm.
4, Numerical Algorithm: Numerical calculation of the container contents.

以下对所有算法进行细致分类并标明功能:
<一>查找算法(13个):判断容器中是否包含某个值
adjacent_find:            在iterator对标识元素范围内,查找一对相邻重复元素,找到则返回指向这对元素的第一个元素的ForwardIterator。否则返回last。重载版本使用输入的二元操作符代替相等的判断。
binary_search:            在有序序列中查找value,找到返回true。重载的版本实用指定的比较函数对象或函数指针来判断相等。
count:                    利用等于操作符,把标志范围内的元素与输入值比较,返回相等元素个数。
count_if:                 利用输入的操作符,对标志范围内的元素进行操作,返回结果为true的个数。
equal_range:              功能类似equal,返回一对iterator,第一个表示lower_bound,第二个表示upper_bound。
find:                     利用底层元素的等于操作符,对指定范围内的元素与输入值进行比较。当匹配时,结束搜索,返回该元素的一个InputIterator。
find_end:                 在指定范围内查找"由输入的另外一对iterator标志的第二个序列"的最后一次出现。找到则返回最后一对的第一个ForwardIterator,否则返回输入的"另外一对"的第一个ForwardIterator。重载版本使用用户输入的操作符代替等于操作。
find_first_of:            在指定范围内查找"由输入的另外一对iterator标志的第二个序列"中任意一个元素的第一次出现。重载版本中使用了用户自定义操作符。
find_if:                  使用输入的函数代替等于操作符执行find。
lower_bound:              返回一个ForwardIterator,指向在有序序列范围内的可以插入指定值而不破坏容器顺序的第一个位置。重载函数使用自定义比较操作。
upper_bound:              返回一个ForwardIterator,指向在有序序列范围内插入value而不破坏容器顺序的最后一个位置,该位置标志一个大于value的值。重载函数使用自定义比较操作。
search:                   给出两个范围,返回一个ForwardIterator,查找成功指向第一个范围内第一次出现子序列(第二个范围)的位置,查找失败指向last1。重载版本使用自定义的比较操作。
search_n:                 在指定范围内查找val出现n次的子序列。重载版本使用自定义的比较操作。

<二>排序和通用算法(14个):提供元素排序策略
inplace_merge:            合并两个有序序列,结果序列覆盖两端范围。重载版本使用输入的操作进行排序。
merge:                    合并两个有序序列,存放到另一个序列。重载版本使用自定义的比较。
nth_element:              将范围内的序列重新排序,使所有小于第n个元素的元素都出现在它前面,而大于它的都出现在后面。重载版本使用自定义的比较操作。
partial_sort:             对序列做部分排序,被排序元素个数正好可以被放到范围内。重载版本使用自定义的比较操作。
partial_sort_copy:        与partial_sort类似,不过将经过排序的序列复制到另一个容器。
partition:                对指定范围内元素重新排序,使用输入的函数,把结果为true的元素放在结果为false的元素之前。
random_shuffle:           对指定范围内的元素随机调整次序。重载版本输入一个随机数产生操作。
reverse:                  将指定范围内元素重新反序排序。
reverse_copy:             与reverse类似,不过将结果写入另一个容器。
rotate:                   将指定范围内元素移到容器末尾,由middle指向的元素成为容器第一个元素。
rotate_copy:              与rotate类似,不过将结果写入另一个容器。
sort:                     以升序重新排列指定范围内的元素。重载版本使用自定义的比较操作。
stable_sort:              与sort类似,不过保留相等元素之间的顺序关系。
stable_partition:         与partition类似,不过不保证保留容器中的相对顺序。

<三>删除和替换算法(15个)
copy:                     复制序列
copy_backward:            与copy相同,不过元素是以相反顺序被拷贝。
iter_swap:                交换两个ForwardIterator的值。
remove:                   删除指定范围内所有等于指定元素的元素。注意,该函数不是真正删除函数。内置函数不适合使用remove和remove_if函数。
remove_copy:              将所有不匹配元素复制到一个制定容器,返回OutputIterator指向被拷贝的末元素的下一个位置。
remove_if:                删除指定范围内输入操作结果为true的所有元素。
remove_copy_if:           将所有不匹配元素拷贝到一个指定容器。
replace:                  将指定范围内所有等于vold的元素都用vnew代替。
replace_copy:             与replace类似,不过将结果写入另一个容器。
replace_if:               将指定范围内所有操作结果为true的元素用新值代替。
replace_copy_if:          与replace_if,不过将结果写入另一个容器。
swap:                     交换存储在两个对象中的值。
swap_range:               将指定范围内的元素与另一个序列元素值进行交换。
unique:                   清除序列中重复元素,和remove类似,它也不能真正删除元素。重载版本使用自定义比较操作。
unique_copy:              与unique类似,不过把结果输出到另一个容器。

<四>排列组合算法(2个):提供计算给定集合按一定顺序的所有可能排列组合
next_permutation:         取出当前范围内的排列,并重新排序为下一个排列。重载版本使用自定义的比较操作。
prev_permutation:         取出指定范围内的序列并将它重新排序为上一个序列。如果不存在上一个序列则返回false。重载版本使用自定义的比较操作。

<五>算术算法(4个)
accumulate:               iterator对标识的序列段元素之和,加到一个由val指定的初始值上。重载版本不再做加法,而是传进来的二元操作符被应用到元素上。
partial_sum:              创建一个新序列,其中每个元素值代表指定范围内该位置前所有元素之和。重载版本使用自定义操作代替加法。
inner_product:            对两个序列做内积(对应元素相乘,再求和)并将内积加到一个输入的初始值上。重载版本使用用户定义的操作。
adjacent_difference:      创建一个新序列,新序列中每个新值代表当前元素与上一个元素的差。重载版本用指定二元操作计算相邻元素的差。

<六>生成和异变算法(6个)
fill:                     将输入值赋给标志范围内的所有元素。
fill_n:                   将输入值赋给first到first+n范围内的所有元素。
for_each:                 用指定函数依次对指定范围内所有元素进行迭代访问,返回所指定的函数类型。该函数不得修改序列中的元素。
generate:                 连续调用输入的函数来填充指定的范围。
generate_n:               与generate函数类似,填充从指定iterator开始的n个元素。
transform:                将输入的操作作用与指定范围内的每个元素,并产生一个新的序列。重载版本将操作作用在一对元素上,另外一个元素来自输入的另外一个序列。结果输出到指定容器。

<七>关系算法(8个)
equal:                    如果两个序列在标志范围内元素都相等,返回true。重载版本使用输入的操作符代替默认的等于操作符。
includes:                 判断第一个指定范围内的所有元素是否都被第二个范围包含,使用底层元素的<操作符,成功返回true。重载版本使用用户输入的函数。
lexicographical_compare:  比较两个序列。重载版本使用用户自定义比较操作。
max:                      返回两个元素中较大一个。重载版本使用自定义比较操作。
max_element:              返回一个ForwardIterator,指出序列中最大的元素。重载版本使用自定义比较操作。
min:                      返回两个元素中较小一个。重载版本使用自定义比较操作。
min_element:              返回一个ForwardIterator,指出序列中最小的元素。重载版本使用自定义比较操作。
mismatch:                 并行比较两个序列,指出第一个不匹配的位置,返回一对iterator,标志第一个不匹配元素位置。如果都匹配,返回每个容器的last。重载版本使用自定义的比较操作。

<八>集合算法(4个)
set_union:                构造一个有序序列,包含两个序列中所有的不重复元素。重载版本使用自定义的比较操作。
set_intersection:         构造一个有序序列,其中元素在两个序列中都存在。重载版本使用自定义的比较操作。
set_difference:           构造一个有序序列,该序列仅保留第一个序列中存在的而第二个中不存在的元素。重载版本使用自定义的比较操作。
set_symmetric_difference: 构造一个有序序列,该序列取两个序列的对称差集(并集-交集)。

<九>堆算法(4个)
make_heap:                把指定范围内的元素生成一个堆。重载版本使用自定义比较操作。
pop_heap:                 并不真正把最大元素从堆中弹出,而是重新排序堆。它把first和last-1交换,然后重新生成一个堆。可使用容器的back来访问被"弹出"的元素或者使用pop_back进行真正的删除。重载版本使用自定义的比较操作。
push_heap:                假设first到last-1是一个有效堆,要被加入到堆的元素存放在位置last-1,重新生成堆。在指向该函数前,必须先把元素插入容器后。重载版本使用指定的比较操作。
sort_heap:                对指定范围内的序列重新排序,它假设该序列是个有序堆。重载版本使用自定义比较操作。

First, the function object: Because many of the algorithms used in the multi-function objects

Binary function object, V1 and V2 is input, V3 is the result

plus:
transform(V1.begin(), V1.end(), V2.begin(), V3.begin(),plus());

Other binary function object: minus, multiples, divieds, modulus.

Two yuan predicate function objects need to use bind2nd () or bind1st () to bind comparison.

less:
find_if(L.begin(), L.end(), bind2nd(less(), 0));

Other binary predicate function: equal_to, notequal_to, greater, greater_equal, less_equal, logical_and, logical_or

Binary logistic functions

binary_negate:
const char* wptr = find_if(str, str + MAXLEN,
compose2(not2(logical_or()),
bind2nd(equal_to(), ’ '),
bind2nd(equal_to(), ‘/n’)));

A unary function object

negate:
transform(V1.begin(), V1.end(), V2.begin(),
negate());

One yuan conclude function object

logical_not:
transform(V.begin(), V.end(), V.begin(), logical_not());

One yuan logic function

unary_negate:

Second, the function object generator: mainly used to fill sequence

产生不重复的随机数:
// Generate unique random numbers from 0 to mod:
class URandGen {
std::set used;
int limit;
public:
URandGen(int lim) : limit(lim) {
srand(time(0));
}
int operator()() {
while(true) {
int i = int(rand()) % limit;
if(used.find(i) == used.end()) {
used.insert(i);
return i;
}
}
}
};

const int sz = 10;
const int max = 50;
vector x(sz), y(sz), r(sz);
//An integer random number generator:
URandGen urg(max);
generate_n(x.begin(), sz, urg);

Third, the object adapter functions: a function into a function object

ptr_fun: general function adapter

One yuan Example:
Transform (First, Last, First,
compose1 (o negate, ptr_fun (FABS)));

Examples of two yuan:
List <char *> :: = Item Iterator
the find_if (L.begin (), L.end (),
Notl (binder2nd (ptr_fun (strcmp), "the OK")));

not1: negated adapter function object to determine a dollar.

not2: determine binary function object adapter negated.

mem_fun and mem_fun_ref: Adapter class member function, a distinction is needed pointer, while the other requires only generic object. As follows:
shape is a pointer variable, foreach (v.begin (), v.end ( ), mem_fun (& shape :: draw));
but if the shape is generally variable, not a pointer, foreach (v.begin ( ), v.end (), mem_fun_ref ( & shape :: draw));

Fourth, the algorithm

Copy:
Copy ()
reverse_copy ()
() rotate_copy
element () to a value ranging copy of remove_copy to another sequence.
remove_copy_if () to copy matches another sequence.

Generating and filling:
Fill ()
fill_n () filled in the sequence of n elements.
generate () call Gen () is a function of each element in the sequence.

Arrangement:
next_permuttion (after) a permutation.
prev_permutation ()

Partition () dividing the element satisfies the condition of the sequence moves to the front.
stable_partition ()

Find and Replace:
Find ()
binary_search () to find the sequence has a sequence.
the find_if ()
Search () checks if the second sequence is present in the first sequence in the same order.

Delete: Attention must call erase () to actually remove
the Remove ()
UNIQUE () delete adjacent duplicate elements, it is now the best sort.

The combined sequence:
Merge ()

Numerical Algorithm:
the accumulate () for summing each element of the sequence is operated.
transform () operation may be performed for each element.
Count:
size () Total number.
the number of elements to a value of count () and the like.

Front and rear adjacent_difference Save a sequence adjacent to a front of his new sequence obtained.

adiacent_find

Fifth, all the algorithms

accumlate: iterator of the elements and the sequence flag, added by a specified initial value init. Overloaded version no longer do the addition, but passed in binary operator is applied to the element.
adjacent_different: Create a new sequence, each new value of the sequence represents the difference between the current elements on an element. Overloaded version of the difference between adjacent elements of the specified calculation binary operation.
adjacent_find: within the range of elements iterator of signs, look for a pair of adjacent repeating element, if find returns a ForwardIterator, pointing to the first element of this element. Otherwise last. Overloaded version using binary operator input instead equal to the determination.
binary_search: Finding value in an ordered sequence, returns true if found. Overloaded version specified comparison function object or function pointer to determine equal.
copy: copy sequence.
copy_backward: In addition to the element to be copied in the reverse order, the other copy, and the same.
count: using the equality operator, the values of the elements of the input range of the flag type is compared, and returns the number of elements equal.
count_if: For elemental indicator range class, the operator inputs the application, and returns the result as the number of true.
equal: If the two sequence elements in the range are equal, the equal returns true. Overloaded version of the operator using the input instead equal to the default operator.
equal_range: Returns a pair iterator, the first iterator returned by the iterator represented lower_bound, the second represents the value returned by the iterator is upper_bound.
fill: copy assigned to each element in a range of input values.
fill_n: the input value is assigned to the first element to the frist n + range.
find: equal to the underlying element by using operator input elements and the values of the range are compared. When a match, the search is finished, a return InputIterator that element.
find_if: using the input function instead of the equality operator performed find.
find_end: Find "by another iterator to mark the second input sequence" is within the range of the last occurrence. Overloaded version of the operator using the user input is equal to the alternative operation.
find_first_of: Find any "by another iterator to the flag input of the second sequence" is in the range of a first element first appears. Overloaded version used in user-defined operators.
for_each: function sequentially executed for all elements of the input range.
generate: calling a function by continuous gen input to fill the specified range.
generate_n: filling n elements.
includes: determining whether an element [first1, last1) is contained in another sequence. Using the underlying elements of <= operator overloaded version of the function using the user input.
inner_product: the inner product of the two sequences (multiplied by the corresponding elements, and then sum), a product is added to the initial value and the input. Use heavy-duty version of the user-defined actions.
inner_merge: merge two rows over a contiguous sequence motif, the sequence covering both ends of the range of the results, using the operation input overloaded version sort.
iter_swap: swap values of ForwardIterator.
lexicographical_compare: comparison of two sequences. Use a heavy-duty version of the user-defined comparison operation.
lower_bound: Returns an iterator, which points in the range of the ordered sequence can be inserted without destroying the value of a specified position of the container sequence. Overloads using custom comparison operation.
max: Returns the larger of the two elements, overloaded version uses a custom comparison operation.
max_element: returns an iterator, noted that the largest element in the sequence. Heavy-duty version using a custom comparison operations.
min: two smaller elements. Heavy-duty version using a custom comparison operations.
min_element: Similar to max_element, but returns the smallest elements.
merge: merge two ordered sequence, and place the other sequence. Heavy-duty version uses a custom comparison.
mismatch: parallel comparison of two sequences indicating a first position does not match, it returns Iterator one pair, a flag does not match the first element position. If a match is returned last each container. Heavy-duty version using a custom comparison operations.
next_permutation: Remove the arrangement of the current range, and reordering for the next order. Heavy-duty version using a custom comparison operations.
nth_element: reordered sequence range, so that all elements smaller than n elements appear in front of it, and are greater than that present in the back, the comparison operation using overloaded version customized.
partial_sort: partial ordering do the entire sequence, the number of elements to be sorted can just be put in the range of. Heavy-duty version using a custom comparison operations.
partial_sort_copy: partial_sort the same, except that the copy to another container through the ordered sequence.
partial_sum: Create a new sequence of elements, where each element represents the value before the position of the range and all the elements. Overloaded version using custom actions alternative adder.
partition: the range of the reordering of elements, using a function of the input, the calculated result is true elements are placed before the result is false elements.
prev_permutation: Remove the sequence and within the scope of it on a reordered sequence. If a sequence does not exist on return false. Heavy-duty version using a custom comparison operations.
random_shuffle: elements for adjusting the range of the random sequence. Overloaded version of a random number generation operation input.
remove: Delete all equal within the range of the specified element Note that this function does not really remove elements. Built-in array and is not suitable for use remove_if remove function.
remove_copy: all elements that do not match are copied to a specified container, returned OutputIterator point to the next location of the end of the element to be copied.
remove_if: Delete input operation result is true element of all ranges.
remove_copy_if: all the elements do not match the copy to a specified container.
replace: all equal old_value elements are used in the range new_value alternative.
replace_copy: replace with similar, but the result is written into another container.
replace_if: all within the scope of the operation result is replaced with a new element of the true value.
replace_copy_if: Similar to replace_if, but the result is written into another container.
reverse: the range of the elements in reverse order to re-press.
reverse_copy: Similar to reverse, but the result is written into another container.
rotate: the range of the element to the end of the container, a middle element pointed to be the first element of a container.
rotate_copy: Similar to rotate, but the result is written into another container.
search: given two ranges, a return Iterator, pointing to a position within the range of the first time sequence. Heavy-duty version using a custom comparison operations.
search_n: Find n times the sequence occurs in the value range. Heavy-duty version using a custom comparison operations.
set_difference: configuration of a row over the sequence motif, wherein the elements present in the first sequence, but is not included in the second sequence. Heavy-duty version using a custom comparison operations.
set_intersection: configuration of a row over the sequence motif, wherein the elements are present in both sequences. Heavy-duty version using a custom comparison operations.
set_symmetric_difference: configuration of a row over the sequence motif, wherein the elements present in the first sequence, but does not appear in the second sequence. Heavy-duty version using a custom comparison operations.
set_union: configuration of a row over the sequence motif, which contains all the elements will not be repeated in the two sequences. Heavy-duty version using a custom comparison operations.
sort: rearranged in ascending order of elements within the range, the comparison operation using overloaded version customized.
stable_partition: partition and the like, but it does not guarantee that the relative order of retention vessel.
stable_sort: Similar to the sort, but the order is equal to the relationship between the retention element.
swap: exchange of values stored in the two objects.
swap_range: The elements within the scope of the exchange with an additional sequence element value.
transform: effect on the operation of each element in the input range, and generates a new sequence. Overloaded version of the operating element acting on a pair, a further sequence of one element from another input. It outputs the result to the specified container.
unique: Clear sequence repeated elements, and remove similar, it can not really delete elements. Use a heavy-duty version of the operating custom.
unique_copy: Similar to unique, but it outputs the result to another container.
upper_bound: Returns an Iterator, which points in the range of the value ordered sequence inserted position of the container without destroying the last sequence, the location flag value is greater than a value. Use a heavy-duty version of the comparison operation input.
Heap algorithm: C ++ standard library provides a max-heap. A total heap algorithm consists of the following four generics.
make_heap: the generation of a range of elements in the stack. Heavy-duty version using a custom comparison operations.
pop_heap: not really focus on the largest element from the heap pop, but reorder the heap. It is the first exchange and the last-1, and then were made into a heap. You can use the container back to visit the "pop" element or to use pop_back really deleted. Heavy-duty version using a custom comparison operations.
push_heap: Suppose first to last-1 is a valid heap, pile elements to be added at a position last-1, regenerate piles. Before the pointing function, must be inserted into the container after the first element. Heavy-duty version using a comparator specify.
sort_heap: sequence reordered in the range, it is assumed that the sequence is ordered stack. Heavy-duty version using a custom comparison operations.

Guess you like

Origin blog.csdn.net/weixin_43615373/article/details/90437601