《C++Primer Plus》 | 复合类型

数组

typeName arrayName[arraySize]

  1. 要求arraySize在编译是已知,不能是变量。
  2. 数组作为由基本类型组成的复合数据类型,arrayName要强调是对应基本数据类型组成的数组(特定数组)
  3. 通过下标或索引单独访问各个元素(可能引发数组越界的问题,int a[20],容易错误访问a[20])
  4. 数组可使用列表初始化,即C++11可省略=
char ch[4]{'0','',65,'5'};
65在char的范围内

字符串

char string[4]={'H','e','r',''};

char string[]="Her";
已空字符结尾的字符数组是字符串,C-风格字符串,第二种是隐式写法,会自动加''

cout << "I am a student.
";
cout <<"I am"   " a student.
";
cout <<"I a"  "m a student.
";

C++允许字符串的拼接,第一个字符串的隐式''会被第二个字符串的第一个字符代替
cstring中含strlen()函数,字符数组的长度不能小于strlen()+1.
cin>> name1
cin>> name2
cin已空格,制表符,换行符确定字符串结束,例如在name1是输入Bob Tom,Bob放到name1,Tom留在输入队列,无需在输入,cin会在输入队列中读取Bob
cin.getline(stringname,num)
以上为将键盘输入写入到stringname[num]的字符数组,num包含''
getline()成员函数按行输入,遇到' '结束,舍弃换行符,get()不舍弃换行符,连续输入采用cin.get(s,num).get()的方式。

cin.getline().getline() //可以看成连续两次调用getline
cin.get().get()//cin.get()返回cin对象,这是一种拼接方式
(cin>>year).get()//处理'
'  year 为int
cin.get(s,num)

string类

#include

string str1;
string str2;
string str3;
cin >> str1;//C++自动调整str1的长度
st2r=str1;
str1=str2+str3;

#include

strcpy(s1,s2)//copy s2 to s1
strcat(s1,s2)//s1+=s2,即append s2 to s1
s1.size()//结果与strlen()等价,但有.说明是对象.类方法(函数)

vector&array模板

#include <iostream>
#include<vector>  //STL C++98 ,动态数组的替代品
#include<array>  //C++11


int main()
{
using namespace std;
double a[4]={1.4,1.2,3.5,6.7};
vector <double> b(4);//个数常量或变量
b[0]=1.4;
b[1]=1.2;
b[2]=3.5;
b[3]=6.7;
array <double,4> c={1.4,1.2,3.5,6.7};
array <double,4> d;//个数必为常量
d=c;
cout << "a[2]:" <<a[2]<<"is located at: "<< &a[2]<< endl;
cout << "b[2]:" <<b[2]<<"is located at: "<< &b[2]<< endl;
cout << "c[2]:" <<c[2]<<"is located at: "<< &c[2]<< endl;
cout << "d[2]:" <<d[2]<<"is located at: "<< &d[2]<< endl;
}

vector对象在自由存储区或堆区,array对象,数组在栈区,array对象可以赋值给另一个对象,数组只能一个一个赋值

new&delete

int * pt=new int ;
delete pt;//不能用delete 连续两次释放同一个内存块
int *pn=new int [10];
delete [] pn;

原文地址:https://www.cnblogs.com/zuoanfengxi/p/13338618.html