array和vector的區別

array

array <typeName, n_element> a;
typeName: 數據類型
a: 對象名
n_element:只能是整形常量

vector

vector v(n_element);
typeName: 數據類型
v: 對象名
n_element:個數,可以是整形變量,或整形常量

#include <iostream>
#include <vector>
#include <array>

int main()
{
	using namespace std;
	double a1[4] = {1.2, 2.4, 3.6, 4.8};
	vector <double> a2(4);
	a2[0] = 1.0 / 3.0;
	a2[1] = 1.0 / 5.0;
	a2[2] = 1.0 / 7.0;
	a2[3] = 1.0 / 9.0;
	
	array <double, 4> a3 = {1.0, 2.0, 3.0, 4.0};
	array <double, 4> a4;
	
	a4 = a3; // 使用這個數組可以直接賦值
	
	cout << "a1[2]" <<a1[2] << " at " << &a1[2] << endl;
	cout << "a2[2]" <<a2[2] << " at " << &a2[2] << endl;
	cout << "a3[2]" <<a3[2] << " at " << &a3[2] << endl;
	cout << "a4[2]" <<a4[2] << " at " << &a4[2] << endl;
	
	a1[-2] = 20.0;
	cout << "a1[-2]" <<a1[-2] << " at " <<  &a1[-2] << endl;
	cout << "a3[2]" <<a3[2] << " at " <<  &a3[2] << endl;
	cout << "a4[2]" <<a4[2] << " at " << &a4[2] << endl;
	return 0;
	
}

編譯結果

a1[2]3.6 at 0x7ffdf4479770
a2[2]0.142857 at 0x55ef51a57e80
a3[2]3 at 0x7ffdf4479790
a4[2]3 at 0x7ffdf44797b0
a1[-2]20 at 0x7ffdf4479750
a3[2]3 at 0x7ffdf4479790
a4[2]3 at 0x7ffdf44797b0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章