转载请注明出处:http://blog.csdn.net/enyusmile/article/details/48677679
本章内容包括:
16.1 string类
16.1.1 构造字符串
构造函数 | 描述 |
---|---|
string(const char *s) | 将string对象初始化为s指向的NBTS |
string(size_type n,char c) | 创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c |
string (const string & str) | 将一个string对象初始化string对象str(复制构造函数) |
string() | 创建一个默认的string对象,长度为0(默认构造函数) |
string(const char *s,size_type n) | 将string对象初始化为s指向的NBTS的前n个字符,即使超过了NBTS结尾 |
template |
将string对象初始化为区间[begin,end]内的字符,其中begin和end的行为就像指针,用于制定位置,范围包括begin在内,但不包括end |
string(const string & str,string size_type pos=0,size_type n=npos) | 将一个string对象初始化为对象str中从位置pos开始到结尾的字符,或从位置pos开始的n个字符 |
string(string && str) noexcept | 这是C++11新增的,它将一个string对象初始化为string对象str,并可能修改str(移动构造函数) |
string(initializer_list |
这是C++11新增的,它将一个string对象初始化为初始化列表il中的字符 |
程序清单16.1 str1.cpp
16.1.2 string类输入
16.1.3 使用字符串
// hangman.cpp -- some string methods
#include
#include
#include
#include
#include
using std::string;
const int NUM = 26;
const string wordlist[NUM] = {"apiary", "beetle", "cereal",
"danger", "ensign", "florid", "garage", "health", "insult",
"jackal", "keeper", "loaner", "manage", "nonce", "onset",
"plaid", "quilt", "remote", "stolid", "train", "useful",
"valid", "whence", "xenon", "yearn", "zippy"};
int main()
{
using std::cout;
using std::cin;
using std::tolower;
using std::endl;
std::srand(std::time(0));
char play;
cout << "Will you play a word game? " ;
cin >> play;
play = tolower(play);
while (play == 'y')
{
string target = wordlist[std::rand() % NUM];
int length = target.length();
string attempt(length, '-');
string badchars;
int guesses = 6;
cout << "Guess my secret word. It has " << length
<< " letters, and you guess\n"
<< "one letter at a time. You get " << guesses
<< " wrong guesses.\n";
cout << "Your word: " << attempt << endl;
while (guesses > 0 && attempt != target)
{
char letter;
cout << "Guess a letter: ";
cin >> letter;
if (badchars.find(letter) != string::npos
|| attempt.find(letter) != string::npos)
{
cout << "You already guessed that. Try again.\n";
continue;
}
int loc = target.find(letter);
if (loc == string::npos)
{
cout << "Oh, bad guess!\n";
--guesses;
badchars += letter; // add to string
}
else
{
cout << "Good guess!\n";
attempt[loc]=letter;
// check if letter appears again
loc = target.find(letter, loc + 1);
while (loc != string::npos)
{
attempt[loc]=letter;
loc = target.find(letter, loc + 1);
}
}
cout << "Your word: " << attempt << endl;
if (attempt != target)
{
if (badchars.length() > 0)
cout << "Bad choices: " << badchars << endl;
cout << guesses << " bad guesses left\n";
}
}
if (guesses > 0)
cout << "That's right!\n";
else
cout << "Sorry, the word is " << target << ".\n";
cout << "Will you play another? " ;
cin >> play;
play = tolower(play);
}
cout << "Bye\n";
return 0;
}
16.1.4 string还提供了哪些功能
16.1.5 字符串种类
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
typedef basic_string<char16_t> u16string;//C++11
typedef basic_string<char32_t> u32string;//C++11
16.2 智能指针模板类
16.2.1 使用智能指针
16.2.2 有关智能指针的注意事项
// fowl.cpp -- auto_ptr a poor choice
#include
#include
#include
int main()
{
using namespace std;
auto_ptr<string> films[5] =
{
auto_ptr<string> (new string("Fowl Balls")),
auto_ptr<string> (new string("Duck Walks")),
auto_ptr<string> (new string("Chicken Runs")),
auto_ptr<string> (new string("Turkey Errors")),
auto_ptr<string> (new string("Goose Eggs"))
};
auto_ptr<string> pwin;
pwin = films[2]; // films[2] loses ownership
cout << "The nominees for best avian baseball film are\n";
for (int i = 0; i < 5; i++)
cout << *films[i] << endl;
cout << "The winner is " << *pwin << "!\n";
// cin.get();
return 0;
}
16.2.3 unique_ptr为何由于auto_ptr
std::unique_ptrpad (new doule(5));//will use delete []
16.2.4 选择智能指针
16.3 标准模板库
16.3.1 模板类vector
template T, class Allocator = allocator<T>>
class vector{...
16.3.2 可对矢量执行的操作
16.3.3 对矢量可执行的其他操作
16.3.4 基于范围的for循环(C++11)
16.4 泛型编程
16.4.1 为何使用迭代器
16.4.2 迭代器类型
16.4.3 迭代器层次结构
16.4.4 概念,改进和模型
// copyit.cpp -- copy() and iterators
#include
#include
#include
int main()
{
using namespace std;
int casts[10] = {6, 7, 2, 9 ,4 , 11, 8, 7, 10, 5};
vector<int> dice(10);
// copy from array to vector
copy(casts, casts + 10, dice.begin());
cout << "Let the dice be cast!\n";
// create an ostream iterator
ostream_iterator<int, char> out_iter(cout, " ");
// copy from vector to output
copy(dice.begin(), dice.end(), out_iter);
cout << endl;
cout <<"Implicit use of reverse iterator.\n";
copy(dice.rbegin(), dice.rend(), out_iter);
cout << endl;
cout <<"Explicit use of reverse iterator.\n";
// vector::reverse_iterator ri; // use if auto doesn't work
for (auto ri = dice.rbegin(); ri != dice.rend(); ++ri)
cout << *ri << ' ';
cout << endl;
// cin.get();
return 0;
}
// inserts.cpp -- copy() and insert iterators
#include
#include
#include
#include
#include
void output(const std::string & s) {std::cout << s << " ";}
int main()
{
using namespace std;
string s1[4] = {"fine", "fish", "fashion", "fate"};
string s2[2] = {"busy", "bats"};
string s3[2] = {"silly", "singers"};
vector<string> words(4);
copy(s1, s1 + 4, words.begin());
for_each(words.begin(), words.end(), output);
cout << endl;
// construct anonymous back_insert_iterator object
copy(s2, s2 + 2, back_insert_iterator<vector<string> >(words));
for_each(words.begin(), words.end(), output);
cout << endl;
// construct anonymous insert_iterator object
copy(s3, s3 + 2, insert_iterator<vector<string> >(words, words.begin()));
for_each(words.begin(), words.end(), output);
cout << endl;
// cin.get();
return 0;
}
16.4.5 容器种类
表达式 | 返回类型 | 说明 | 复杂度 |
---|---|---|---|
X::iterator | 指向T的迭代器类型 | 满足正向迭代器要求的任何迭代器 | 编译时间 |
X::value_type | T | T的类型 | 编译时间 |
X u; | 创建一个名为u的空容器 | 固定 | |
X(); | 创建一个匿名的空容器 | 固定 | |
X u(a); | 调用复制构造函数后u==a | 线性 | |
X u=a; | 作用同X u(a); | 线性 | |
r=a; | X& | 调用赋值运算符后r==a | 线性 |
(&a)->~X(); | void | 对容器中每个元素应用析构函数 | 线性 |
a.begin() | 迭代器 | 返回指向容器第一个元素的迭代器 | 固定 |
a.end() | 迭代器 | 返回超尾值迭代器 | 固定 |
a.size() | 无符号整型 | 返回元素个数,等价于a.end()-a.begin() | 固定 |
a.swap(b) | void | 交换a和b的内容 | 固定 |
a==b | 可转换为bool | 如果a和b的长度相同,且a中每个元素都等于(==为真)b中相应的元素,则为帧 | 线性 |
a!=b | 可转换bool | 返回!(a==b) | 线性 |
2.C++11新增的容器要求
表达式 | 返回类型 | 说明 | 复杂度 |
---|---|---|---|
X u(rv); | 调用移动构造函数后,u的值与rv的原始值相同 | 线性 | |
X u=rv; | 作用同Xu(rv); | ||
a=rv; | X& | 调用移动赋值运算符后,u的值与rv的原始值相同 | 线性 |
a.cbegin() | const_iterator | 返回指向容器第一个元素的const迭代器 | 固定 |
a.cend | const_iterator | 返回超尾值const迭代器 | 固定 |
如果源对象是临时的,移动操作的效率将高于常规复制.
16.4.4 关联容器
16.4.5 无序关联容器(C++11)
16.5 函数对象
16.5.1 函数符概念
16.5.2 预定义的函数符
警告:老式C++实现使用函数符名times,而不是multiplies.
16.5.3 自适应函数符和函数适配器
STL有5个相关的概念:自适应生成器adaptable generator,自适应一元函数adaptable unary function,自适应二元函数adaptable binary function,自适应为此adaptable predicate和自适应二元为此adaptable binary predicate.
16.6 算法
16.6.1 算法组
16.6.2 算法的通用特征
16.6.3 STL和string类
16.6.4 函数和容器方法
16.6.5 使用STL
//usealgo.cpp -- using several STL elements
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
char toLower(char ch) { return tolower(ch); }
string & ToLower(string & st);
void display(const string & s);
int main()
{
vector<string> words;
cout << "Enter words (enter quit to quit):\n";
string input;
while (cin >> input && input != "quit")
words.push_back(input);
cout << "You entered the following words:\n";
for_each(words.begin(), words.end(), display);
cout << endl;
// place words in set, converting to lowercase
set<string> wordset;
transform(words.begin(), words.end(),
insert_iterator<set<string> > (wordset, wordset.begin()),
ToLower);
cout << "\nAlphabetic list of words:\n";
for_each(wordset.begin(), wordset.end(), display);
cout << endl;
// place word and frequency in map
map<string, int> wordmap;
set<string>::iterator si;
for (si = wordset.begin(); si != wordset.end(); si++)
wordmap[*si] = count(words.begin(), words.end(), *si);
// display map contents
cout << "\nWord frequency:\n";
for (si = wordset.begin(); si != wordset.end(); si++)
cout << *si << ": " << wordmap[*si] << endl;
// cin.get();
// cin.get();
return 0;
}
string & ToLower(string & st)
{
transform(st.begin(), st.end(), st.begin(), toLower);
return st;
}
void display(const string & s)
{
cout << s << " ";
}
16.7 其他库
16.7.1 vector,valarray和array
16.7.2 模板initializer_list(C++11)
16.7.3 使用initializer_list
16.8 总结
16.9 复习题
本章源代码下载地址