c++ 11中提供了数组类Array(容器)该Array的引入引入为C风格的数组提供了更好的选择。array类相对于C风格的数组有以下的优点:
1. 数组类(Array class)知道自己的大小,而C风格的数组缺乏此属性。所以当传递给函数时,我们不需要把数组的大小作为单独的参数传递。
2. 使用C风格的数组,数组退化为指针的风险更大;而数组类不会衰退为指针。
3. Array通常比C风格的数组更有效、更轻、更可靠。
array是什么? 就是一个定长数组 可以把对象当成一个数组名
注意事项:
-
容器统一不用指针去操作,而是用里面内置的迭代器去操作
-
array数组和一维数组一样使用,只是它是一个模版类(用类描述的数组)
-
data() 返回第一个元素的地址 ,string 里面的 data() 相当于 c_str() 转换成为字符串
1、提供迭代器打印
void printArray(array<int, 3> &Array)
{
for (array<int, 3>::iterator it = Array.begin(); it != Array.end(); it++)
{
cout << *it << "\t";
}
cout << endl;
}
2、遍历数组的三种方法
void test01()
{
array<int, 3> myArray = { 1,2,3 };
// array<int,3> *pInt=new array<int,3>; 语法麻烦,但是不怎么常用
for (auto v : myArray)
{
cout << v << "\t";
}
cout << endl;
for (array<int, 3>::iterator it = myArray.begin(); it != myArray.end(); it++)
{
cout << *it << "\t";
}
cout << endl;
for (int i = 0; i < 3; i++)
{
cout << myArray[i] << "\t";
}
cout << endl;
}
3、单独访问数组中的元素
/* 判断*/
void arrayFunc()
{
array<string, 3> strArray = { "julia","andy","lisa" };
cout << "size=" << strArray.size() << endl;
cout << strArray.empty() << endl;
// 1、使用下标法进行访问
cout << strArray[1] << endl;
// 2、功能: front() 返回当前array容器中起始元素的引用
// back() 返回当前vector容器中末尾元素的引用。
cout << strArray.front() << endl;
cout << strArray.back() << endl;
// 3、使用迭代器
cout << *strArray.begin() << endl;
cout << *(strArray.end()-1) << endl;
//cout << *(--strArray.end()) << endl;//打印最后一个元素
// 4、使用at
cout << strArray.at(1) << endl;
}
4、交换两个容器
//size保持一致
void test02()
{
array<int, 3> myArray1 = { 1,2,3 };
array<int, 3> myArray2 = { 10,20,30 };
cout << "交换前" << endl;
printArray(myArray1);
printArray(myArray2);
myArray1.swap(myArray2);
cout << "交换后" << endl;
printArray(myArray1);
printArray(myArray2);
}