C++ Primer笔记——explicit、string流、vector比较、emplace

目录

一.P265 抑制构造函数定义的隐式转换

二.P287 string流

三.P304 vector的比较

四.P307 在容器中特定位置添加元素


一.P265 抑制构造函数定义的隐式转换

举个例子,如果构造函数参数是string类型,那么当使用赋值符号进行初始化操作时,实际上是将string隐式转换成临时目标类,再将临时对象通过拷贝构造给真正对象。

当不希望发生隐式类型转换时,需要使用explicit关键字。

class A {
	string str;
public:
	explicit A(const string& _str)
		:str(_str)
	{}
};

string s = "hello";
A a(s);//正确
A a("hello");//正确
A a = s;//错误

使用explicit有几点需要注意:

1.只能用于构造函数

2.只能用于单参数构造函数

3.类外定义构造函数时不能重复书写。

4.可以显式强制转换。

A a = static_cast<A>(s);

二.P287 string流

使用string流时,初始化对象形式可能如下:

string str = "hello";
stringstream ss(str, ios_base::out);

这里需要注意,ss是将str拷贝了一份,并不是直接使用str。 

因此使用时不管是读还是写,都是对那份拷贝的string操作,不影响str本身内容。

ss << "world";
cout << str << endl;
cout << ss.str();

三.P304 vector的比较

如果是对vector对象直接比较,那么会有以下比较顺序:

1.从下标0处开始比较

2.先按元素大小进行比较

3.如果大小全部相同,按数组长度比较

vector<int> a = { 1, 2, 3, 4 };
vector<int> b = { 1, 2, 3, 4 };
vector<int> c = { 1, 3, 3, 4 };
vector<int> d = { 1, 2, 3, 4, 5, 6 };

a == b//true
a > c//false,c值大于a
a == d//false, a长度小于d

四.P307 在容器中特定位置添加元素

C++中对于范围的操作,均秉持着左闭右开原则,即[ , )。

因此,许多函数的参数含义一目了然。

比如insert当参数为迭代器时,含义是插入此迭代器前一个位置,符合“右开”。很好理解,因为insert支持迭代器为end(),而end代表结尾的下一个位置,此位置自然是不能插入数据的,因此是插入前一个位置。 

返回值是新元素的位置。

emplace函数可以很好代替push和insert函数,因为emplace的形参是万能引用,既支持左值也支持右值

 因此,当使用右值传参时,不需要拷贝,能节省资源。

同时,参数还是可变参数,这样emplace就支持一些push所不能完成的:

class A {
	string str;
	int i;
	double d;
public:
	A(const string& _str, int _i, double _d)
		:str(_str)
		,i(_i)
		,d(_d)
	{}
};

vector<A> v;
v.insert(v.begin(), A("hello", 1, 3.14));//正确
v.insert(v.begin(), "hello", 1, 3.14);//错误
v.emplace(v.begin(), "hello", 1, 3.14);//正确


如有错误,敬请斧正

猜你喜欢

转载自blog.csdn.net/weixin_61857742/article/details/128274841