"C++primer (fifth Edition)" Learning Road-Tenth chapter: Generic Algorithm __web

Source: Internet
Author: User

"Statement: All rights reserved, reproduced please indicate the source, do not use for commercial purposes." Contact Email: libin493073668@sina.com "


10.1 Overview


1. Most algorithms are defined in the header file algorithm. The standard library also defines a set of numerical generic algorithms in file numeric.


10.2 Initial Generic algorithm


1.

Accumulate: defined in header file numeric. The effect is to sum the range.

EUQAL: defined in header file algorithm. The function is to determine whether a given two intervals are equal.

Fill: defined in header file algorithm. The effect is to give a value to a given interval.

Fill_n: defined in header file algorithm. The effect is to assign a value to n elements after a given iterator.

Back_inserter: defined in header file iterator. Gets the iterator that points to the tail of the container.

Sort: defined in the header file algorithm. Sorts the specified interval.

Unique: defined in header file algorithm. "Eliminate" duplicates, returning an iterator that points to the end of a range of distinct values.

Erase: defined in header file algorithm. Deletes the element within the specified range.


10.3 Custom Operations


1. A predicate is a callable expression whose return result is a value that can be used as a condition. Predicates are divided into: unary predicates and two-dollar predicates. A few meta predicates accept several arguments.


2. Callable object definition; For an object or an expression, if the invocation operator can be used on it, it is called callable, and the callable object has: a function, a function pointer, a class that has an overloaded function call operator, and a lambda expression.
Lambda expression in the form of:
[Capture List] (parameter list)->return type{function body};
The capture list is a listing of the local variables defined in the function where the lambda is located (usually empty);
return type, parameter list, and function body are returned types, parameter lists, and functional bodies, respectively.


3. Standard library bind function

Header file: Functional; It accepts a callable object and generates a new callable object to accommodate the argument list of the original object.
Call bind in the form of:
Auto Newcallable=bind (callable, arg_list);
The newcallable itself is a callable object, Arg_list is a comma-delimited list of arguments corresponding to the given callable parameters. The parameters in Arg_list may contain the name of the _n, _1 is the first parameter of newcallable, _2 is the second argument, and so on.


4.bind copy parameters and cannot copy ostream. We can use the ref function.

Function ref returns an object that contains the given reference, which can be copied. Standard library CNOOC A cref function that generates a class that holds a const reference. Like bind, function ref and CREF are also defined in header file functional.


10.4 Re-probing the iterator


1.

Insert iterators: These iterators are bound to a container that can be used to insert elements into the container.

Stream iterators: These iterators are bound to input or output streams and can be used to traverse all associated IO streams.

Reverse iterators: These iterators move backwards rather than forwards. There are reverse iterators in the standard library containers except Forward_list.

Move iterators: These dedicated iterators do not copy the elements but move them.


2.

Back_inserter Create an iterator that uses push_back

Front_inserter Create an iterator that uses Push_front

Inserter creates an iterator that uses inserts. This function accepts the second argument, which must be a pointer to a given container.

Iterators. The element is inserted before the element represented by the given iterator.


3.

Istream_iterator operation

Istream_iterator<t> in (was) in from the input stream is reading a value of type T

Istream_iterator<t> end; Istream_iterator iterator that reads a value of type T, representing the trailing position

in1 = = in2 in1 and in2 must read the same type. If they are both trailing iterators, or bound to the same

in1!= in2 Input, the two are equal

*in returns the value read from the stream

In->mem and (*in). Mem have the same meaning

++in,in++ reads the next value from the input stream using the >> operator defined by the element type. As always, the predecessor returns a reference to the incremented iterator, and the back version returns the old value


4.

Ostream_iterator operation

Ostream_iterator<t> out (OS); Out writes a value of type T to the output stream OS

Ostream_iterator<t> out (os,d); Out writes the value of type T to the output stream OS, and outputs a d after each value. D an array of characters that point to the end of a null character

out = Val; Use the << operator to write Val to the ostream that is bound by out. The type of Val must be compatible with the out writable type.

*out,++out,out++; These operators are present, but do nothing with out. Each operator returns out


10.5 Generic algorithm structure


1. Iterator category

Input iterator is read-only, not write, single scan, only increment

Output iterators write only, do not read, single scan, only increment

Forward iterator can read and write, multiple scans, can only increment

Bidirectional iterators can read and write, multiple scans, can be progressively decreasing

Random access iterators can read and write, multiple scans, support all iterator operations


10.6 Specific container algorithms


1.

Algorithms for list and forward_list member function versions

Lst.merga (LST2)

Lst.megra (Lst2,comp) merges elements from Lst2 into LST. Both LST and lst2 must be orderly. The element will be removed from the lst2. After the merge, the lst2 becomes empty. The first version uses the < operator; The second version uses the given comparison operation.

Lst.remove (Val)

LST.REMOVE_IF (pred) calls erase deletes each element that is equal to the given value (= =) or that makes the unary predicate true

Lst.reverse () Reverses the order of elements in LST

Lst.sort ()

Lst.sort (comp) to sort elements using < or given comparison operations

Lst.unique ()

Lst.unique (pred) calls erase deletes a continuous copy of a unified value. The first version uses = =; The second version uses the given two-dollar predicate


2.

Parameters for splice member functions of list and forward_list

Lst.splice (args) or flst.splice_after (args)

(P,LST2) p is an iterator that points to an element in LST, or an iterator that points to the first position of the flst. The function moves all elements of the lst2 to the position before p in LST or the position after p in Flst. Removes the element from the Lst2. Lst2 must be of the same type as LST or FLST, and cannot be the same list.

(P,LST2,P2) P2 is a valid iterator that points to the position in the Lst2. Move the element that P2 points to lst, or move the elements after P2 to flst. Lst2 can be the same linked list as LST or flst.

(p,lst2,b,e) B and E must indicate the legal scope of the LST2. Moves the elements in a given range from Lst2 to LST or flst. Lst2 and LST (or FLST) can be the same linked list, but p cannot point to elements in a given range.



PS: Part of the exercise answer


Practice 10.1 & 10.2

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <list>

int main ()
{
	std::vector<int> Vec = {1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,5};
	Std::cout << "ex 10.1:" << Std::count (Vec.cbegin (), Vec.cend (), 5) << "Times" << Std::endl;
	
	std::list<std::string> lst = {"A", "AA", "AA", "AA"};
	Std::cout << "Ex 10.2:" << Std::count (Lst.cbegin (), Lst.cend (), "AA") << "Times" << std::endl;< C11/>return 0;
}

Practice 10.3 & 10.4

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

int main ()
{
	std::vector<int> Ivec = {1,2,3,4,5};
	Std::cout << "ex 10.3:" << std::accumulate (Ivec.cbegin (), Ivec.cend (), 0) << Std::endl;
	
	Std::vector<double> Dvec = {1.1,2.2,3.3,4.4,5.5};
	Std::cout << "ex 10.4:" << std::accumulate (Dvec.cbegin (), Dvec.cend (), 0) << Std::endl;
	Std::cout << "ex 10.4:" << std::accumulate (Dvec.cbegin (), Dvec.cend (), double (0)) << Std::endl;
	
	return 0;
}

Exercise 10.5

#include <algorithm>
#include <iostream>
#include <vector>
#include <list>

int main ()
{
	std::vector<const char*> roster1{"One", "two", "three"};
	Std::list<const char*> roster2{"One", "two", "three", "four", "Five"};
	
	Std::cout << std::equal (Roster1.cbegin (), Roster1.cend (), Roster2.cbegin ()) << Std::endl;

Exercise 10.6

#include <algorithm>
#include <iostream>
#include <vector>

int main ()
{
	Std::vector<int> Ivec {1,2,3,4,5,6,7,8,9,10};
	Std::fill_n (Ivec.begin (), Ivec.size (), 0);
	for (auto I:ivec)
		std::cout << i << "";
	Std::cout << Std::endl;
}

Exercise 10.7

A. Run error, correct for

Vector<int> Vec;
list<int> lst;
int i;
while (Cin >> i) lst.push_back (i);
Vec.resize (Lst.size ());
Copy (Lst.cbegin (), Lst.cend (), Vec.begin ());

B. No errors, but Vec or empty, reserve only changes the maximum capacity of VEC, the current capacity can be saved unchanged

Exercise 10.9

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

template <typename sequence> auto println (Sequence const& seq)->
std::ostream& {for
	(auto const& elem:seq)
		std::cout << elem << "";
	return std::cout << Std::endl;
}

Auto Elimdups (std::vector<std::string>& vs)-> std::vector<std::string>&
{
	std:: Sort (Vs.begin (), Vs.end ());
	println (VS);

	Auto New_end = Std::unique (Vs.begin (), Vs.end ());
	println (VS);

	Vs.erase (New_end,vs.end ());
	Return vs.
}

int main ()
{
	std::vector<std::string> vs {"A", "V", "a", "s", "V", "a", "a"};
	println (VS);
	println (Elimdups (VS));
	return 0;
}

Exercise 10.11

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <list>

template <typename sequence> inline std::ostream & println (Sequence const& seq)
{for
	(auto const& elem:seq)
		std::cout << elem << ""; return
	std::cout;
}

inline bool Is_shorter (std::string const& lhs,std::string const&)
{return
	RHS () < Rhs.size ();
}

void Elimdups (std::vector<std::string>& vs)
{
	std::sort (Vs.begin (), Vs.end ());
	Auto New_end = Std::unique (Vs.begin (), Vs.end ());
	Vs.erase (New_end,vs.end ());
}

int main ()
{
	std::vector<std::string> vec {"1234", "1234", "1234", "Hi", "Alan", "Wang"};
	Elimdups (VEC);
	Std::stable_sort (Vec.begin (), Vec.end (), is_shorter);
	Std::cout << "ex 10.11:" << Std::endl;
	println (VEC);
	return 0;
}
Exercise 10.12

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include "ex7_26.h"

inline bool Compareisbn (const sales_data& D1,const sales_data& D2)
{return
	D1.ISBN () <d2.isbn ();
}

int main ()
{
	sales_data d1 ("AA"), D2 ("AAAA"), D3 ("AAA"), D4 ("Z"), D5 ("Aaaaz");
	Std::vector<sales_data> VEC {d1,d2,d3,d4,d5};

	Std::sort (Vec.begin (), Vec.end (), COMPAREISBN);

	for (const auto& Elem:vec)
		std::cout << elem.isbn () << "";
	Std::cout << Std::endl;
	return 0;
}
Exercise 10.13

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

BOOL Predicate (const std::string& s)
{return
	s.size () >=5;
}

int main ()
{
	Auto VEC = std::vector<std::string>{"A", "AAAA", "AASAA", "BBBBBBB", "CCC"};
	Auto PIVOT = std::p artition (Vec.begin (), Vec.end (), predicate);
	for (Auto it = Vec.begin (); it!=pivot;++it)
	std::cout << *it << "";
	Std::cout << Std::endl;
	
	return 0;
}
Exercise 10.14

Auto add = [] (int lhs,int rhs) {return lhs+rhs;};
Exercise 10.15

int a = ten;
Auto Add = [a] (int b) {return a+b;};
Exercise 10.16

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

void Elimdups (std::vector<std::string>& vec)
{
	sort (vec.begin (), Vec.end ());
	Auto New_end = Std::unique (Vec.begin (), Vec.end ());
	Vec.erase (New_end,vec.end ());
}

void Biggies (std::vector<std::string> vec,std::size_t sz)
{
	using std::string;
	
	Elimdups (VEC);
	
	Std::stable_sort (Vec.begin), Vec.end (), [] (String const& lhs,string const& rhs) {return lhs.size () < Rhs.size ();});
	
	Auto WC = find_if (Vec.begin (), Vec.end (), [sz] (string const&lhs) {return lhs.size () >=sz;});
	
	Std::for_each (Wc,vec.end (), [] (const string& s) {std::cout << s << "";});
	Std::cout << Std::endl;
}

int main ()
{
	std::vector<std::string> vec {"1234", "1234", "1234", "hi~", "Alan", "Alan", "CP"};
	Biggies (vec,3);
	Std::cout << Std::endl;
	return 0;
}

Exercise 10.17

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include "ex7_26.h"

int main ()
{
	sales_data d1 ("AA"), D2 ("AAAA"), D3 (" AAA "), D4 (" Z "), D5 (" Aaaaz ");
	Std::vector<sales_data> VEC {d1,d2,d3,d4,d5};

	Std::sort (Vec.begin (), Vec.end (), [] (const-sales_data& d1,const sales_data& D2) {return D1.ISBN () <D2.ISBN () ;});

	for (const auto& Elem:vec)
		std::cout << elem.isbn () << "";
	Std::cout << Std::endl;
	return 0;
}

Practice 10.18 & 10.19

#include <iostream> #include <string> #include <vector> #include <algorithm>//from ex 10.9 Void
	Elimdups (std::vector<std::string>& vs) {Std::sort (Vs.begin (), Vs.end ());
	Auto New_end = Std::unique (Vs.begin (), Vs.end ());
Vs.erase (New_end, Vs.end ());

	}//ex10.18 void Biggies_partition (std::vector<std::string>& vs, std::size_t sz) {elimdups (VS);
	Auto Pivot = partition (Vs.begin (), Vs.end (), [SZ] (const std::string& s) {return s.size () >= sz;

	});

for (Auto it = Vs.cbegin (); it!= pivot ++it) std::cout << *it << "";}

	ex10.19 void Biggies_stable_partition (std::vector<std::string>& vs, std::size_t sz) {elimdups (VS);
	Auto pivot = stable_partition (Vs.begin (), Vs.end (), [SZ] (const std::string& s) {return s.size () >= sz;

	});

for (Auto it = Vs.cbegin (); it!= pivot ++it) std::cout << *it << "";} int main () {//ex10.18 std::vector<std::string> v {"The", "quick"," Red "," Fox "," jumps "," over "," the "," Slow "," Red "," turtle "};
	Std::cout << "ex10.18:";
	Std::vector<std::string> v1 (v);
	Biggies_partition (v1, 4);

	Std::cout << Std::endl;
	ex10.19 std::cout << "ex10.19:";
	Std::vector<std::string> v2 (v);
	Biggies_stable_partition (v2, 4);

	Std::cout << Std::endl;
return 0; }

Exercise 10.20

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

std::size_t bigerThan6 (std::vector<std::string> vec)
{return
	count_if (Vec.begin (), Vec.end (), [] (std::string const& s) {return s.size () >6;});

int main ()
{
	std::vector<std::string> vec{"Alan",    "moophy",  "1234567", "1234567", "1234567 "," 1234567 "};
    Std::cout << bigerThan6 (VEC) << Std::endl;
}

Exercise 10.21

#include <iostream>
#include <string>
#include <vector>
#include <algorithm >

int Main ()
{
	int i = 7;
	Auto fun = [&i] ()
	{return
		--i?false:true;
	};
	while (!fun ())
		std::cout << i << "";
	Std::cout << Std::endl;
}

Exercise 10.22

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std::p laceholders;

BOOL IsBigerThan6 (std::string& s,std::size_t sz)
{return
	s.size () >6;
}

int main ()
{
	std::vector<std::string> vec {"Alan", "Moophy", "1234567", "1234567", "1234567", "1234567 "};
	Std::cout << count_if (Vec.begin (), Vec.end (), bind (isbigerthan6,_1,6)) << Std::endl;

Exercise 10.22

 #include <iostream> #include <string> #include <vector> #include <

Algorithm> #include <functional> using namespace std::p laceholders;

inline bool Check_size (const std::string& S,std::string::size_type sz) {return s.size () <sz;} Inline Std::vector<int>::const_iterator find_first_bigger (const std::vector<int>& VEC,CONST std::

string& s) {return find_if (Vec.cbegin (), Vec.cend (), bind (check_size,s,_1));
	int main () {std::vector<int> vec{1,2,3,4,5,6,7};
	std::string s ("test"); STD:: 

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.