mixtypes.cpp: some type combinations #include <iostream> struct antarctica_year_end { int year; /* some really interesting data, etc. */ }; int main() { using namespace std; antarctica_year_end s01, s02, s03; s01.year = 1998; antarctica_year_end * pa = &s02; pa->year; antarctica_year_end trio[3]; trio[0].year = 2003; cout << trio->year << endl; const antarctica_year_end * arp[3] = {&s01, &s02, &s03}; cout << arp[1]->year << endl; const antarctica_year_end ** ppa = arp; auto ppb = arp; /* const antarctica_year_end ** ppb = arp; */ cout << (*ppa)->year << endl; cout << ((*ppb + 1))->year << endl; return 0; } 1. 編譯輸出: 2003 1 1998 0 2. 代碼詳解:
choices.cpp: array variations #include <iostream> #include <vector> #include <array> int main() { using namespace std; // C, original C++ double al[4] = {1.2, 2.4, 3.6, 4.8}; // C++98 STL vector<double> a2(4); // no simple way to initialize in C98 a2[0] = 1.0 / 3.0; a2[1] = 1.0 / 5.0; a2[2] = 1.0 / 7.0; a2[3] = 1.0 / 9.0; // C+11 -- create and initialize array object array<double, 4> a3 = {3.14, 2.72, 1.62, 1.41}; array<double, 4> a4; a4 = a3; // use array notation cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl; cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl; cout << "a3[2]: " << a3[2] << " at " << &a4[2] << endl; cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl; //misdeed a1[-2] = 20.2; cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl; cout << "a3[2]: " << a3[2] << " at " << &a4[2] << endl; cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl; return 0; } 數(shù)組的幾種替代品:
無論是數(shù)組,、vector還是array對象,都可使用標(biāo)準(zhǔn)數(shù)組表示法來訪問各個元素,。 array對象和數(shù)組存儲在相同的內(nèi)存區(qū)域(即棧)中,,而vector對象存儲在另一個區(qū)域(自由存儲區(qū)或堆)中。 |
|