既然要学习数组,那么先来了解一下数组是什么,为什么要有数组的出现吧。
数组:数组是一系列具有相同类型元素的集合。
数组的出现是为了当定义较多变量时,使操作更简单化,直观化。
静态数组与动态数组
*静态数组:*在编译阶段,数组包含的元素数以及占用的内存量是不变的。
可分为:一维数组与多维数组
一维数组的定义:
int numbers[200]={0};
char mycharacters[5];
多维数组的定义:
int ThreeRowsThreeCols [3][3]={{1,2,3},{4,5,6},{7,8,9}};
动态数组:静态数组在未知数量的情况下,需要分配大量的内存。而动态数组为了减少占用内存,在运行阶段根据需要增大动态数组。
动态数组的定义需要用到:vector<数据类型>
下面是动态数组的实例:创建一个int类型的动态数组,并动态的增大容量
#include "stdafx.h"
#include"iostream"
#include"string"
#include "vector"
using namespace std;
int main()
{
vector<int> dynArrNums (3);
dynArrNums[0] = 1;
dynArrNums[1] = 3;
dynArrNums[2] = 4;
cout << "the size of array : " << dynArrNums.size() << endl;
int otherdynArraynums = 0;
cout << "Enter the otherdynArraynums";
cin >> otherdynArraynums;
dynArrNums.push_back(otherdynArraynums);
cout << "the size of array : " << dynArrNums.size() << endl;
system("pause");
return 0;
}
结果如下图所示:
注意:
1 静态数组声明定义后,他们的长度在编译阶段是固定不变的,它既不能存储更多的数据,即使有部分元素未被使用,它的内存空间也不会减少。
2 在定义静态数组时,务必初始化数组,否则会包含未知数值。
3 访问数组元素时,注意索引应该比最大长度少1,不应超越数组的边界。
4在使用动态数组时,务必添加头文件 # include "vector"
C风格的字符串和c++字符串:std:string
C风格的字符串
下面用一个简单的例子解释:
#include "stdafx.h"
#include "iostream"
using namespace std;
int main()
{
char Sayhellotoc[] = { 'h','e','l','l','o',' ','\0' };
cout << "the size of Sayhellotoc : " << sizeof(Sayhellotoc) <<endl;
cout << "the length of Sayhellotoc : " << strlen(Sayhellotoc) << endl;
Sayhellotoc[4] = '\0';
cout << "the size of Sayhellotoc : " << sizeof(Sayhellotoc) << endl;
cout << "the length of Sayhellotoc : " << strlen(Sayhellotoc) << endl;
system("pause");
return 0;
}
输出结果如下图所示:
注意:
由以上输出的结果可知:
1 定义的变量类型为char,在初始化字符串时,末尾必须有 ‘\0’。
2 ‘\0’只会占据字符串内存空间的大小,不会影响字符串的长度。
3 在给已知的字符串分配内存空间的大小,数组的长度=字符串的长度+1
4 字符串的中间插入‘\0’时,数组的长度不会改变,但是字符串的长度会减少 。
c++字符串:std:string
同样用一个例子来解释:
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
string SayhellotoC("hello");
cout << "the size of the SayhellotoC : " << SayhellotoC.length() << endl;
system("pause");
return 0;
}
结果如下图所示:
注:
从上面结果可以看出:
1定义类型为string,与char不同。
2 不需要在末尾添加‘\0’,也不需要像C形式,一个一个的初始化字符串,更加简单、快捷;同时也防止了忘记添加转义字符而超越数组的边界;
3 需要引入头文件 #include “string”
4 当查看字符串长度时与C不同,运用 stingname.length形式查看。