chapter 16

Posted 孤灯下的守护者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了chapter 16相关的知识,希望对你有一定的参考价值。

Chapter 16 

# string class Constructors (Page 952)

string(const char *s)
string(size_type n, char c)
string(const string &str)
string()
string(const char *s,size_type n)
template<class Iter>
string(Iter begin, Iter end)
string(const string &str,size_type n = npos)
string(string && str) noexcept //c++11
string(initializer_list<char> il) //c++11

# string class input

C-style:

char info[100];
cin >> info; // read a word
cin.getline(info,100); // read a line,discard \n
cin.get(info,100); // read a line,leave \n in que

string object:
string stuff;
cin >> stuff; // read a word
getline(cin,stuff); //read a line, discard \n

cin.getline(info,100,‘:‘);
getline(stuff,‘:‘); // read up to :, discard :

# Working with Strings

if (snake1.length() == snake2.size() )
...
size() and length() return same result.

size_type find(const string & str,size_type pos = 0)const
size_type find(const char *s,size_type pos = 0) const
size_type find(const char *s,size_type pos = 0, size_type n)
size_type find(char ch,size_type pos = 0) const

rfind(),find_first_of(),find_last_of(),find_first_not_of(),
find_last_not_of().

capacity() method returns the size of thr current block, and
the reserve() method allows to request a minimum size for
the block.

fout.open(filename.c_str()); //using c_style string


# Smart Pointer Template Classes
#
smart pointer is a class object that acts like s pointer but has
additional features. //using destructor free memory

auto_ptr c++98 //deprecates in c++11
unique_ptr shared_ptr

# using smart pointers

#include <memory>
template<class X> class auto_ptr {
public:
explicit auto_ptr( X *p = 0) throw();
...};

for example:
auto_ptr<double> pd(new double);
auto_ptr<string> ps(new string);

string vacation("I wandered lonely as a cloud.");
share_ptr<string> pvac(&vacation); // NO !!!!
// when pvac expires, the program would apply the delete
operator to non_heap memory, which is wrong.


# why auto_ptr being desprecated?
auto_ptr<string> ps(new string("I lonely."));
aout_ptr<string> vocation;
vocation = ps; // will crash when running, core dump
here,when ps and vocation both expires, use delete twice.
solution:
ownership: unique_ptr //find problem by compiler
if a propram attempt to assign one unique_ptr
to another,the compiler allows it if the
source object is a temporary rvalue and disal-
lows it if the source object has some duration
:
using namespace std;
unique_ptr<string> pul(new string "Hi ho");
unique_ptr<string>pu2;
pu2 = pu1; // not allowed
unique_ptr<string> pu3;
pu3 = unique_ptr<string>(new string "yo");
// allowed

reference counting: shared_ptr
the shared_ptr template includes an explicit
constructor for converting an rvalue
unique_ptr to a shared_ptr.(page 978)

#
# The Standard Template Library
#
The STL provides a collection of templates representing
containers,iterators,function objects, and algorithms.

# The vector Template class

** All the STL containers provide basic methods: size(),
** swap(), begin(),end(). predefined iterator type.
** erase(): scores.erase(scores.begin(),scores.end()+2);
** insert():
old_v.insert(old_v.begin(),new_v.begin(),new_v.end());
# STL function:
for_each(),random_shuffle(),sor() (page 987)
# for ( auto x : books) show(x);


#
# Generic Programming
#

# kinds of iterators :
input output randomaccess forward bidirectional

# copy(),ostream_iterator and istream_iterator

int casts[5] = {6,2,5,6,4};
vector<int> dice[5];
copy(casts,casts+5,dice.begin());

#include <iterator>
ostream_iterator<int, char> out_iter(cout," ");

// *out_iter++ = 15; //works like cout << 15 << " ";

copy(dice.begin(),dice.end(),out_iter);//display
same like this:
copy(dice.begin(),dice.end(),
ostream_iterator<int, char>(cout," "));

similarly:

copy(istream_iterator<int,char>(cin),
istream_iterator<int,char(),dice.begin());
istream_iterator<int,char>() indicates input failure.

others:
reverse_iterator,back_insert_iterator,front_insert_
iterator and insert_iterator.

To create a back_insert_iterator for a vector<int>
container called dice:
back_insert_iterator<vector<int> > back_iter(dice);
insert_iterator<vector<int>> insert_iter(dice,
dice.begin() );

#example:

copy(s2,s2+5,back_insert_iterator<vector<string> >
(words));
#
# Kinds of Containers
#
STL has both container concepts and container types.
The concepts are general categories with names such
as container,sequence container,and associative container
The container types are templates you can use to create
specific container objects.The original 11 container
types are:
deque,list,queue,priority_queue,stack,vector,map,
multimap,set,multiset, and bitset.

# Container Concepts

Container is an objects that stores other objects,
which are all of a single type.
####################################################
table 16.5(page 1008) Some Basic container Properties

X::iterator
X::value_type
X u;
X();
X u(a);
X u = a;
r = a; // r is a value of type x&
(&a)->~X(); // Applies destructor to every element
// of a container
a.begin()
a.end()
a.size()
a.swap(b)
a == b
a != b
#####################################################
more added c++11

X u(rv);
X u = rv;
a = rv;
a.cbegin())
a.cend()
####################################################

# Sequences: in strict linear order

deque forward_list(c++11),list,queue,priority_queue,
stack,and vector //array class is sequence too.
######################################################
table 16.7 sequence requirements
X a(n,t) //n copies of value t
x(n,t)
x a(i,j) //range [i,j)
x(i,j)
a.insert(p,t) //insert t before p
a.insert(p,n,t) //insert n copies of t before p
a.insert(p,i,j) //range insert
a.erase(p) //erase the element pointed to by p
a.erase(p,q) //range [p,q)
a.clear() //same as erase(begin(),end())
#######################################################
Optional Sequence Requirements
a.front() //vector,list,deque
a.back() // above same
a.push_front(t) //list,deque
a.push_back(t) //vector list deque
a.pop_front(t) //list deque
a.pop_back(t) //vector list deque
a[n] //vector deque
a.at(n) //vector deque //do bounds check
######################################################
vector emphasizes rapid access via random access
list emphasizes rapid insertion and removal

table 16.9 Some list Member Functions

void merge(list<t>, Alloc>& x) //x is left empty
void remove(const T & val)
void sort()
void splice(iterator pos,list<T,Alloc> x)
//insert list x before pos,x is left empty
void unique()
#######################################################
table 16.10 queue operations

bool empty() const //return true if empty
size_type size() const //return number of element
T& front() //return front value
T& back() //return back value
void push(const T& x) //insert to back
void pop() //removes the front value
#######################################################

#
# Associative Containers : using some kind of tree.
#
An associative container associates a value with a
key and uses the key to find the value.

A tree is a data structure in which a root node is
linked to one or two other nodes.

The STL provides four associative containers:
set,multiset,map,multimap
#include <set> or include <map> header

for set the value is the key. //value is unique
multiset have more than one value with same key
// value can repeat

## set and multiset key and value type must be same

## for map type, the value is different from key


set_union(A.begin(),A.end(),B.begin(),B.end(),
ostream_iterator<string,char>out(cout," "));

set_union(A.begin(),A.end(),B.begin(),B.end(),
insert_iterator<set<string> >(C, C.begin()));

set_intersection() set_diferece() function same like
set_union(). find same or different values.

lower_bound() and upper_bound() method:
takes a key_type value, return an iterator.

insert() for set just take a value argument because
can sort automatically.

#
# A multimap
#
multimap<int,string> codes; //int as key,string value

to keep information together, STL uses a
pair<class T,class U> template. for example:

pair<const int, string> item(213,"Los Ange");
codes.insert(item);
or:
codes.insert(pair<const int,string>(213,"Los Ang");

Given a pair object, can access the two compoent by
using first and second members:

pair<const int, string> item(213, "Los Ange");
cout << item.first<< " " << item.second <<endl;

count() member function takes a key, returns the
number of items that have that key

lower_bound(), upper_bound() take a key work as set do

equal_range() member function takes a key and returns
iterators representing the range matching that key. In
order to return two value, the method packages them
into a pair object.

for example:

pair<multimap<KeyType,string>::iterator,
multimap<keyType,string>::iterator> range
= codes.equal_range(718);
cout << "cities with area code 718:\n";
std::multimap<KeyType,std::string>::iterator it;
for (it = range.first; it != range.second; ++it)
cout << (*it).second << endl;

or:
auto range = codes.equal_range(718);
cout << "Cities with area code 718:\n";
for (auto it = range.first; it != range.second;++it)
cout << (*it).second << endl;
#
# Unordered Associative Containers (c++11)
#
The underlying differenc is that associative contain-
ers are base on tree structures,whereas unordered ass-
ociative containers are base on another form of date
structure called a hash table.
includes:
unordered_set,unordered_mutlset,unordered_map,
and unordered_multimap.
#########################################################

# Function Objects (a.k.a. Functors)

A generator is a functor called no arguments.
A unary function is a functor called with one argument
A binary function is a functor with two arguments

A unary function that return a bool value is a predicate.
A binary function that return a bool value is a binary predicate.

for example:

bool WorseThan(const Review &r1,const Review &r2);
...
sort(books.begin(),books.end(),WorseThan);

// The list template has a remove_if() member that
takes a predicate as an argument.

# Predifined Function

const int LIM = 5;
double arr1[LIM] = {36,39,42,45,48};
vector<double> gr8(arr1,arr1+LIM);
ostream_iterator<double,char> out(cout," ");

transform(gr8.begin(),gr8.end(),out,sqrt);

#This code calculates the square root of each element
#and sends the resulting values to the output stream.

# another version of transform uses a function that take
# two arguments, applying the function to one element
# from each of two ranges.It takes an additional argu-
# ment, which comes third in order,identifying the start
# of the second range.

for example:
transform(gr8.begin(),gr8.end(),m8.begin(),out,
mean);
the functional(formerly function.h) header defines
several template class function objects,including one
called plus<>().

#include <functional>
...
plus<double> add;
double y = add(2.2,3.4); // using plus<double>::operator() ()
but it makes easy like this:

transform(gr8.begin(),gr8.end(),m8.begin()),out,
plus<double>());
#########################################################
table 16.12 page 1032
--------------------------
+ plus
- minus
* multiplies //older c++ use times
/ divides
% modulus
- negate
== equal_to
!= not_equal_to
> greater
< less
>= greater_equal
<= less_equal
&& logical_and
|| logical_or
! logical_not
---------------------------

#########################################################

STL has automated the process with the binder1st and
binder2nd classes,which convert adaptable binary fun-
ction to adaptable unary functions.

binder1st(f2,val) f1; //val is a particular value
// use as first argument of f2

then:
invoking: f1(x) with a single argument

so ,that means:
f1(x) is equivalent to f2(val,x)

#
# Algorithms
#

sort(),copy(),find(),for_each(),random_shuffle()
set_union(),set_intersection(),set_difference(),
transform().

first:
they use templates to provide generic types.
second:
they use iterators to provide a generic re-
presentation for accessing data in a container.

 

The STL divides the algorithm library int four groups:
1, Nonmodifying sequence opreations //find(),for_each().
2, Mutating sequence operations //random_shuffle(),copy().
3, Sorting and related operations //set operations
4, Generalized numeric operations//sum,product ..

#1 - 3 in algorithm header file (formerly algo.h),
#4 is numeric header file (formerly, algo.h)
#
# General Properties of Algorithms
#
Some algorithm come in two version:
an in-place version
and a copying version. //STL append _copy to name
for example:
# in-place version:
template<classd ForwardIterator, class T>
void replace(ForwardIterator first, ForwardIterator last,
const T&old_value,const T&new_value); //in-place

#The copy version is:

template<class InputIterator, class OutputIterator
, class T>
OutputIterator replace_copy(InputIterator first,
InputIterator last,OutputIterator result,
const T& old_value,const T& new_value);
# Another common variation is that some function have
# a version that performs an action conditionally,de-
# pending on the result of applying a function to a
# container element. These version append _if to name.

template<class ForwardIterator, class Predicate,
class T>
void replace_if(ForwardIterator first, Forward-
Iterator last,Predicate pred, const T&
new_value);
# There‘s also a version called replace_copy_if().
# ###################
# The STL and the string Class
#
The string class,although not part of the STL,is
designed with the STL in mind.

next_permutation() is ascending alphabetical order.
return true or false if the range already is in the
final sequence.
To get all of the range,use sort() function first.
# Functions Versus Container Methods
Usually, the method is the better choice. Because it
can resize the container automatically.(remove method
for example). Nonmethod function remove(),however, has
to use erase() to resize. the remove() returns past-the-
end iterator.(page 1040 more detail)

#
# Using the STL
#
The STL is a library whose parts are designed to work
together.The STL components are tools, but they are
also building blocks to create other tools.
####################
#
# Other Libraries (page 1045)
#
# vector,valarray, and array

valarry<double> vad1(10),vad2(10),vad3(10);
vad3 = log(vad1);
or:
vad3 = vad1.apply(log); //apply() method works for
//non-overloaded functions.
vad3 = 10.0 * ((vad1 + vad2)/2.0 + vad1 * cos(vad2));
# valarray class also provides a sum(),a size(),a
# max() method and min() method as while.

valarray<bool> vbool = number > 9;
slice(1,4,3) // start,numberof element,stride
so,here meams select four elements whose indexes are
1,4,7,10 (page 1049)

#
# The initializer_list Template (C++11)
#
#include <initializer_list>
can use begin(),end(),size() members.
the iterator types for initalizer_list are const.

*dl.begin() = 2011.6; // not allowed
the intended use of the initializer_list class is to
pass a list of values to a constructor or some other
function

以上是关于chapter 16的主要内容,如果未能解决你的问题,请参考以下文章

C++ Primer笔记16---chapter13 代码实例

C++ Primer笔记16---chapter13 代码实例

Introduction to GIS Chapter16

Chapter16:实例Vector

Chapter 16_2 继承

Chapter 2 Open Book——16