C++中自带了一些常用的类,以下做部分介绍。
string类是C++中的字符串类,区别于C的字符串,其更具有类的特点。
- string类与字符指针/C语言风格的字符串的不同string类的构造函数
string类有7种不同参数列表的构造函数:
| string(const char *s) | 将string对象初始化为字符指针s指向的以空字符结束的字符串(null-terminated string,NBTS),实际是传统的C风格字符串。 |
| string(int n, char c) | 将string对象初始化为由n个字符c组成的字符串。 |
| string(const string &str) | 将string对象初始化为string类对象str |
| string() | 创建一个默认string对象,长度为0。 |
| string(const char *s, int) | 将string对象初始化为NBTS的前n个字符组成的字符串 |
| template | 将string对象初始化为迭代器(如指针)begin与end之间(包括begin不包括end)的字符串 |
| string(const string &str, int pos, intn) | 将string对象初始化为str从pos到结尾或从pos开始的n个字符的字符串 |
· cin、getline()作为string对象的输入方法比较
C风格字符串的输入与string类对象的输入有些不同,前者可以使用cin、cin.getline()、cin.get(),而后者只能使用cin、getline()。cin.getline()是istream类方法,而getline()则是string类自身的方法。
示例代码如下:
#include#include using namespace std; int main() { string objStr; cout<<"Please enter a string:"< >objStr; cout<<"Here is the input string by using cin:"< getline()方法中的cin是作为参数的,并且其会把换行符从缓冲区中删除;cin中的cin则是调用对象,其会把换行符留在缓冲区中。
string类的方法
string类包含有许多实用的成员函数,例如find()、find_first_of()、find_last_of()等。
以下介绍各类方法。其他方法的重载特征标同find()。
· find()
find()具有以下重载:
int find(const string &str, int pos=0) const 从字符串对象的pos位置开始查找子串str的位置,若找到则返回该子串首字母首次出现的位置索引;若找不到则返回string::npos(即字符串可储存的最大字符数) int find(const char *s, int pos=0) const 从字符串对象的pos位置开始查找子串s的位置,若找到则返回该子串首字母首次出现的位置索引;若找不到则返回string::npos(即字符串可储存的最大字符数) int find(const char *s, int pos=0,int n) const 从字符串对象的pos位置开始,查找字符串s前n个字符组成的子串的位置,若找到则返回该子串首字母首次出现的位置索引;若找不到则返回string::npos(即字符串可储存的最大字符数) int find(char ch, int pos=0) const 从字符串对象的pos位置开始,查找字符ch,若找到则返回该字符首次出现的索引;若找不到则返回string::npos(即字符串可储存的最大字符数)
· find_first_of()
该函数用于寻找子串str中的任意字符在string对象中首次出现的位置,如hahhah在hand中的索引即为0,其调用语句为:string hand=string("hand"); hand.find_first_of("hahhah")
· find_last_of()
该函数用于寻找子串str中的任意字符在string对象中最后出现的位置,如hahhah在hand中的索引即为1。
· find_first_not_of()
该函数用于寻找string对象中不出现在子串str的字符的首次出现的位置,如以下代码的结果是2,n为不在hahhah中:string hand=string("hand"); hand.find_first_not_of("hahhah")· find_last_not_of()
该函数用于寻找string对象中不出现在子串str的字符的最后出现的位置。
C++11提供了智能指针这一新特性来解决动态内存管理的问题,智能指针有auto_ptr、unique_ptr、shared_ptr三种,这些指针过期时,它们将自动调用析构函数使用delete来释放内存。它们均包含在头文件memory中。
- auto_ptr、unique_ptr、shared_ptr的不同
· 释放内存的策略
使用动态内存分配时,当指针均指向同一个对象,可能使得同一个动态内存被释放两次,这样会报错。auto_ptr、unique_ptr、shared_ptr三种智能指针使用了不同的策略:
#auto_ptr、unique_ptr采取的策略是所有权(ownership)策略,只有拥有所有权的智能指针才能访问、delete对象。但是unique_ptr比auto_ptr更智能,因为它能够在写代码时提醒使用者将一个unique_ptr对象A赋给另一个unique_ptr对象B是非法的,从而避免在后续运行时发生无法访问B的问题。auto_ptr是被C++11舍弃的。
#shared_ptr采取的是引用计数策略,即跟踪引用特定对象的智能指针数,当最后一个指针过期时才允许delete对象。
· new、new []
#auto_ptr、shared_ptr使用的是delete来释放动态内存,故只有使用new时才能使用auto_ptr、shared_ptr。
#unique_ptr使用delete或者delete []释放动态内存,故使用hew或new []时都能使用。
智能指针的使用
智能指针的使用代码如下:
//示例
int main()
{
auto_ptr aptr(new string("HH"));
cout<<*aptr;
cin.get();
return 0;
}
-----输出-----
HH 智能指针的选择#在可以使用unique_ptr时,应尽量避免使用auto_ptr,因为它不是那么好。
#当使用了new时,应使用shared_ptr,其适用于需要使用多个指针指向同一对象的场景,包括:用于寻找数组种的最大/最小元素、指向一个被两个对象同时包含的对象、包含指针的STL容器等。
#当使用了new []时,应使用unique_ptr



