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

时间: 2024-10-29 19:06:02

chapter 16的相关文章

《JavaScript高级程序设计》Chapter 15 canvas + Chapter 16 HTML5

Chapter 15 Canvas Chapter 16 HTML5 Chapter 15 Canvas <canvas>元素:设定区域.JS动态在这个区域中绘制图形. 苹果公司引导的.由几组API构成. 2D上下文普及了.WebGL(3D上下文)还未足够普及. 基本用法 首先:width.height属性确定绘图区域大小.后备信息放在开始和结束标签之间. getContext():DOM获得这个canvas元素对象.再在这个对象上调用getContext()获取上下文,传入参数表示获取的是2

零元学Expression Blend 4 - Chapter 16 用实例了解互动控制项「Button」II

原文:零元学Expression Blend 4 - Chapter 16 用实例了解互动控制项「Button」II 本章将教大家如何制作自己的Button,并以玻璃质感Button为实作案例. ? 本章将教大家如何制作自己的Button,并以玻璃质感Button为实作案例 ? ? 01 拉出一个圆 请以Ellipse拖拉出一个圆形,并修改圆形的颜色 范例: Fill->Gradient brush->Radial gradient(0%.#FFFF0000)(100%#FF000000) ?

零元学Expression Blend 4 - Chapter 16 用实例了解交互控件&ldquo;Button&rdquo;II

本章将教大家如何制作自己的Button,并以玻璃质感Button为实践案例. 本章将教大家如何制作自己的Button,并以玻璃质感Button为实践案例 01 拉出一个圆 请以Ellipse拖拉出一个圆形,并修改圆形的颜色 范例: Fill->Gradient brush->Radial gradient(0%.#FFFF0000)(100%#FF000000) 02 把圆形转换成控件 选取圆形,并且在圆形上单击鼠标右键->Make Into Control 点选Button以及命名完成

Chapter 16 Auto layout: Programmatic Constraints

1. The line of code regarding translating constraints has to do with an older system for scaling interfaces - autoresizing masks. Before Auto Layout was introduced, iOS applications used autoresizing masks to allow views to scale for different-sized

Head first java chapter 16 集合与泛型(数据结构)

大气散射 GPU Gems2 Chapter 16. Accurate Atmospheric Scattering

效果图 这次先上效果图*4 散射概念 光线击中空气中的微小颗粒后的偏折导致了光线的散射.我们看到的阳光应该是由视线上的散射在视线方向上的集合.如果由地面的反射,还要加上经过散射计算的地面反射. Rayleigh散射 由较小的空气分子引起的散射,对不同波长的光有不同的散射程度,蓝色最强.也就是天空为啥是蓝色的原因. Mie散射 由较大的漂浮颗粒(气溶胶--PM2.5????)导致的散射 相位方程 相位方程描述有多少光会倍散射到相机方向上. θ:采样点处光线(太阳到采样点)和视线(相机到采样点)的角

chapter 16 网络编程

套接字:通讯端点什么是套接字? 书上说的端口是数据结构和I/O缓存区"是指硬件端口,网络编程里的端口可以理解为应用程序的ID. 说得形象点,套接字就类似我们人类的门我们打开门,通过门外面的人可以进来我们推开门,里面的人也可以出去同样,外面的数据可以通过socket把它存储在本地机器的缓冲区里等待本地机器接收本地机器的数据可以通过socket放在缓冲区里等待发送到对方机器上当我们把门给关上时,就拒绝了和外面世界的交往. 套接字是一种具有之前所说的"通讯端点"概念的计算机网络数据

Chapter 5 MySQL Server Administration_1

Chapter 5 MySQL Server Administration Table of Contents 5.1 The MySQL Server 5.1.1 Configuring the Server 5.1.2 Server Configuration Defaults 5.1.3 Server Option and Variable Reference 5.1.4 Server Command Options 5.1.5 Server System Variables 5.1.6

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W