简体   繁体   English

C ++字符串\\向量初始化

[英]C++ String\ Vector initialization

I have questions about C++ initialization. 我对C ++初始化有疑问。

In Java: if I want a empty StringBuffer, I should use 在Java中:如果我想要一个空的StringBuffer,我应该使用

StringBuffer sb = new StringBuffer();

to initialize a empty string buffer. 初始化一个空的字符串缓冲区。

In C++: If I want to use a empty string, I can just declare 在C ++中:如果我想使用空字符串,则可以声明

std::string str; 

or std::string str = ""; std::string str = "";

In real world projects should I always write like the second form? 在现实世界中的项目中,我应该总是像第二种形式那样写作吗?

How about declare an empty vectors? 如何声明一个空向量?

vector<int> vec;

Is this OK? 这个可以吗? or should I give some null values to this vec? 或者我应该给这个vec一些空值?

std:string and std:vector are classes, not basic types: That mean that unlike an Integer which as a pseudo-random value at the declaration moment, string and vectors has a well defined initial value. std:string和std:vector是类,而不是基本类型:这意味着与Integer不同,Integer在声明时为伪随机值,string和vector具有明确定义的初始值。

The default value for std::string is "". std :: string的默认值为“”。

The default content for std::vector is {}. std :: vector的默认内容为{}。

You may use what you prefer, but the initialization is not necessary, and even not very optimal. 您可以使用自己喜欢的方法,但是初始化不是必需的,甚至不是非常理想的。

  1. std::string str(""); std :: string str(“”); It does a direct initialization and uses string(const char *) constructor. 它直接进行初始化,并使用string(const char *)构造函数。

  2. std::string str=""; std :: string str =“”; It does a copy initialization. 它执行复制初始化。

  3. std::string str; std :: string str; It creates empty string. 它创建空字符串。

Option 3 is just like others and less overhead. 选项3与其他选项一样,开销也较小。 Use it Read more about the difference from here What's the motivation behind having copy and direct initialization behave differently? 使用它从这里了解更多区别。 复制和直接初始化的行为背后的动机是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM