C ++ 11 added some convenient algorithms and 11 new algorithms

Source: Internet
Author: User

C ++ 11 added some convenient algorithms and 11 new algorithms

C ++ 11 has added some convenient algorithms. These new algorithms make our code more concise and convenient. Here, we only list some common new algorithms, for more new algorithms, see http://en.cppreference.com/w/cpp/algorithm.

Three algorithms all_of, any_of, and none_of are added to the Algorithm Library:

template< class InputIt, class UnaryPredicate >bool all_of( InputIt first, InputIt last, UnaryPredicate p );template< class InputIt, class UnaryPredicate >bool any_of( InputIt first, InputIt last, UnaryPredicate p );template< class InputIt, class UnaryPredicate >bool none_of( InputIt first, InputIt last, UnaryPredicate p );
  • All_of: Check whether all elements in the range [first, last) meet the one-dimensional limit p. If all elements meet the conditions, true is returned. Otherwise, false is returned.
  • Any_of: Check whether at least one element in the interval [first, last) meets the one-dimensional p-type. If one element meets the condition, true is returned. Otherwise, true is returned.
  • None_of: Check whether all elements in the range [first, last) do not meet the one-dimensional p. If all elements do not meet the conditions, true is returned. Otherwise, false is returned.

The following is an example of these algorithms:

#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){       vector<int> v = { 1, 3, 5, 7, 9 };    auto isEven = [](int i){return i % 2 != 0;       bool isallOdd = std::all_of(v.begin(), v.end(), isEven);       if (isallOdd)              cout << "all is odd" << endl;       bool isNoneEven = std::none_of(v.begin(), v.end(), isEven);       if (isNoneEven)              cout << "none is even" << endl;       vector<int> v1 = { 1, 3, 5, 7, 8, 9 };       bool anyof = std::any_of(v1.begin(), v1.end(), isEven);       if (anyof)              cout << "at least one is even" << endl;}

Output:

all is oddnone is oddat least one is even

The search algorithm of the algorithm library adds a find_if_not, which has the opposite meaning as find_if, that is, to find elements that do not meet a certain condition. find_if can also implement the find_if_not function, you only need to change the negative encoding type to the negative one. Now, after find_if_not is added, you do not need to write negative encoding, and the readability is also better. The basic usage is as follows:

# Include <iostream> # include <algorithm> # include <vector> using namespace std; int main () {vector <int> v = {1, 3, 5, 7, 9,4}; auto isEven = [] (int I) {return I % 2 = 0 ;}; auto firstEven = std: find_if (v. begin (), v. end (), isEven); if (firstEven! = V. end () cout <"the first even is" <* firstEven <endl; // if you use find_if to search for an odd number, you need to re-write the negative expression auto isNotEven = [] (int I) {return I % 2! = 0 ;}; auto firstOdd = std: find_if (v. begin (), v. end (), isNotEven); if (firstOdd! = V. end () cout <"the first odd is" <* firstOdd <endl; // use find_if_not to find the odd number, so you do not need to define a new sequence auto odd = std :: find_if_not (v. begin (), v. end (), isEven); if (odd! = V. end () cout <"the first odd is" <* odd <endl ;}

Output:

the first even is 4the first odd is 1the first odd is 1

As you can see, using find_if_not does not need to define the negative expression, which is easier.

The Algorithm Library also adds a copy_if algorithm, which is more convenient to use than the original copy algorithm. below is its basic usage:

# Include <iostream> # include <algorithm> # include <vector> using namespace std; int main () {vector <int> v = {1, 3, 5, 7, 9, 4}; std: vector <int> v1 (v. size (); // copy auto it = std: copy_if (v. begin (), v. end (), v1.begin (), [] (int I) {return I % 2! = 0;}); // reduce the vector to the appropriate size v1.resize (std: distance (v1.begin (), it); for (int I: v1) {cout <I <"" ;}cout <endl ;}

Iota is added to the algorithm library to easily generate ordered sequences. For example, if we need a fixed-length array, the elements in this array are incremented based on a specific value, so iota can easily generate this array. The basic usage is as follows:

# Include <numeric> # include <array> # include <vector> # include <iostream> using namespace std; int main () {vector <int> v (4 ); // cyclically traverse and assign values to initialize the array // for (int I = 1; I <= 4; I ++) // {// v. push_back (I); // initialize the array directly through iota, which is more concise: std: iota (v. begin (), v. end (), 1); for (auto n: v) {cout <n <'';} cout <endl; std: array <int, 4> array; std: iota (array. begin (), array. end (), 1); for (auto n: array) {cout <n <'';} std: cout <endl ;}

Output:

1 2 3 41 2 3 4

It can be seen that iota is more concise to initialize the array than to assign values through traversal. It should be noted that the iota initialization sequence needs to specify the size, if the above Code: vector <int> v (4 ); if the initialization size is not specified as 4, the output is null.

The Algorithm Library also adds an algorithm minmax_element that obtains the maximum and minimum values at the same time. If we want to obtain the maximum and minimum values, we do not need to call the max_element and max_element algorithms separately, it is more convenient to use. minmax_element puts the iterator of the minimum and maximum values in a pair and returns the result. The basic usage of minmax_element is as follows:

#include <iostream>#include <algorithm>#include <vector>using namespace std;int main() {    // your code goes here    vector<int> v = { 1, 2, 5, 7, 9, 4 };    auto result = minmax_element(v.begin(), v.end());       cout<<*result.first<<" "<<*result.second<<endl;    return 0;}

Output:

1 9

The is _ sorted and is _ sorted_until algorithms are added to the algorithm library. is_sort is used to determine whether a sequence is sorted, and is_sort_until is used to return part of the sequence that has been sorted before. Below are their basic usage:

#include <iostream>#include <algorithm>#include <vector>using namespace std;int main() {    vector<int> v = { 1, 2, 5, 7, 9, 4 };    auto pos = is_sorted_until(v.begin(), v.end());       for(auto it=v.begin(); it!=pos; ++it)    {        cout<<*it<< " ";    }    cout<<endl;        bool is_sort = is_sorted(v.begin(), v.end());    cout<< is_sort<<endl;    return 0;}

Output:

1 2 5 7 90

Summary: these new algorithms make it easier to use and enhance code readability.


C language is called an algorithm. Algorithms play an important role in programming.

1. What is an algorithm?
Algorithms are a series of clear instructions for solving problems, that is, they can obtain the required output within a limited period of time for certain standard input. Algorithms often contain repeated steps and comparison or logical judgment. If an algorithm has a defect or is not suitable for a problem, executing the algorithm will not solve the problem. Different algorithms may use different time, space, or efficiency to accomplish the same task. The advantages and disadvantages of an algorithm can be measured by space complexity and time complexity.
The time complexity of an algorithm refers to the time resources that the algorithm consumes. Generally, a computer algorithm is a function f (n) of the problem scale n. The growth rate of Algorithm Execution Time is positively related to the growth rate of f (n), which is called Asymptotic Time Complexity ). Time complexity is expressed by "O (order of magnitude)", which is called "order ". Common time complexity: O (1) constant order, O (log2n) Logarithm order, O (n) linear order, O (n2) Square order.
The space complexity of an algorithm refers to the space resources that the algorithm consumes. The computation and Representation Methods are similar to the time complexity. They are generally expressed by the approximation of the complexity. Compared with time complexity, the analysis of space complexity is much simpler.

Ii. Algorithm Design Method
1. Progressive Method
The progressive method is a method that uses the recursive relationship of the question itself to solve the question. If N = 1, the solution is known or can be easily obtained. The issue of constructing an algorithm by means of the progressive method has an important recursive nature, that is, when the problem scale is the solution of the I-1, the recursive nature of the problem can be obtained from the obtained scale of 1, 2, ..., A series of solutions of I-1, the structure of the problem scale for the I solution. In this way, the program can start from I = 0 or I = 1, repeatedly, from known to the I-1 scale of the solution, through recursion, to obtain the scale of the I solution, until the solution with a scale of N is obtained.
[Problem] factorial calculation
Problem description: write a program to calculate and output the factorial k of k for the given n (n ≤ 100! (K = 1, 2 ,..., N.
Because the required integer may be much larger than the digits of a general integer, the program uses a one-dimensional array to store long integers. Each element of a long integer array stores only one digit of a long integer. Store m-bit integer N in array:
N = a [m] × 10m-1 + a [M-1] × 10m-2 +... + A [2] × 101 + a [1] × 100
Use a [0] to store the m digits of the long integer N, that is, a [0] = m. As agreed above, each element of the array stores the factorial k of k! The second and third elements of the array from the low to the high ....... Example: 5! = 120, the storage format in the array is:
3 0 2 1 ......
The first element 3 indicates that the long integer is a three-digit number, followed by 0, 2, and 1 from the low position to the high position, and expressed as an integer 120.
Calculate the factorial k! Can use the obtained factorial (k-1 )! After the continuous accumulation of K-1 obtained. For example, known 4! = 24, calculate 5 !, You can add four times to the original 24 and then get 120. For details, see the following procedure.
# Include <stdio. h>
# Include <malloc. h>
......
2. Recursion
Recursion is a powerful tool for designing and describing algorithms. Because it is often used in the description of complex algorithms, we will discuss it before introducing other algorithm design methods.
Algorithms that can use recursive descriptions usually have the following features: To solve the N-scale problem, we try to break it down into smaller-scale problems, then, we can easily construct solutions to big problems from the solutions to these small problems, and these smaller problems can also be decomposed into smaller problems using the same decomposition and synthesis methods, then, we can deconstruct these smaller problems to solve large-scale problems. In particular, when the scale N is 1, it can be directly solved.
[Problem] compile the nth function fib (n) for calculating the Fibonacci series ).
Fibonacci series: 0, 1, 1, 2, 3 ,......, That is:
Fib (0) = 0;
Fib (1) = 1;
Fib (n) = fib (n-1) + fib (n-2) (when n> 1 ).
Recursive functions:
Int ...... remaining full text>

C language algorithm question?

There are many
Search by yourself,
Are you in college? There are a lot of books like this,
Reading a real book is better than reading it online.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.