龙空技术网

C++|静态、动态数组、数组类、vector类的比较与实例

小智雅汇 415

前言:

此刻看官们对“c语言动态数组定义”都比较注重,咱们都想要剖析一些“c语言动态数组定义”的相关知识。那么小编同时在网络上搜集了一些有关“c语言动态数组定义””的相关内容,希望兄弟们能喜欢,兄弟们快快来学习一下吧!

相同的数据类型集中、邻近存储,顺序访问,可以全用静态数组、动态数组、array类和vector类来实现。区别如下:

1 静态数组

静态数组是具有固定元素个数的群体,其中的元素可以通过下标直接访问。

缺点:大小在编译时就已经确定,在运行时无法修改。

#include <iostream>using namespace std;int foo [] = {16, 2, 77, 40, 12071};int n, result=0;int main (){ for ( n=0 ; n<5 ; ++n ) { result += foo[n]; } cout << result; return 0;}//12206
2 动态数组

动态数组由一系列位置连续的,任意数量相同类型的元素组成。

优点:其元素个数可在程序运行时改变。

#include <iostream>#include <new>using namespace std;int main (){ int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p= new (nothrow) int[i]; if (p == nullptr) cout << "Error: memory could not be allocated"; else { for (n=0; n<i; n++) { cout << "Enter number: "; cin >> p[n]; } cout << "You have entered: "; for (n=0; n<i; n++) cout << p[n] << ", "; delete[] p; } return 0;}/*How many numbers would you like to type? 5Enter number : 75Enter number : 436Enter number : 1067Enter number : 8Enter number : 32You have entered: 75, 436, 1067, 8, 32,*/
3 array类

template < class T, size_t N > class array;

与其他标准容器不同,array类具有固定的大小,并且不通过分配器管理其元素的分配:它们是封装固定大小元素数组的聚合类型。因此,它们不能动态地展开或收缩(有关可以展开的类似容器,请参见vector向量)。

#include <iostream>#include <array>int main (){ std::array<int,10> myarray; // assign some values: for (int i=0; i<10; i++) myarray.at(i) = i+1; // print content: std::cout << "myarray contains:"; for (int i=0; i<10; i++) std::cout << ' ' << myarray.at(i); std::cout << '\n'; return 0;}
4 vector类

template < class T, class Alloc = allocator<T> > class vector;

与数组一样,向量为其元素使用连续的存储位置,这意味着也可以使用指向其元素的常规指针上的偏移量来访问其元素,而且访问效率与数组相同。但与数组不同的是,它们的大小可以动态变化,容器会自动处理它们的存储。在内部,向量使用动态分配的数组来存储元素。

与其他动态序列容器(deques、list和forward_list)相比,向量非常有效地访问其元素(就像数组一样),并相对有效地从其末尾添加或删除元素。对于涉及在除结尾以外的位置插入或删除元素的操作,它们的性能比其他操作差,并且与列表和前向列表相比,迭代器和引用的一致性更低。

#include <iostream>#include <vector>int main (){ std::vector<int> myvector (3,100); std::vector<int>::iterator it; it = myvector.begin(); it = myvector.insert ( it , 200 ); myvector.insert (it,2,300); // "it" no longer valid, get a new one: it = myvector.begin(); std::vector<int> anothervector (2,400); myvector.insert (it+2,anothervector.begin(),anothervector.end()); int myarray [] = { 501,502,503 }; myvector.insert (myvector.begin(), myarray, myarray+3); std::cout << "myvector contains:"; for (it=myvector.begin(); it<myvector.end(); it++) std::cout << ' ' << *it; std::cout << '\n'; return 0;}

//myvector contains: 501 502 503 300 300 400 400 200 100 100 100

5 array与vector支持的成员方法

array与vector支持的成员方法包括构造、析构、容量大小、访问、修改、迭代器等方面:

-End-

标签: #c语言动态数组定义