三种定义数组的方式:分别是C语言的定义方式、STL vector和C++11的array对象。
附源代码:
#include <iostream> #include <vector> // STL C++98 #include <array> // C++11 int main() { using namespace std; // C, original C++ double a1[4] = {1.2, 2.4, 3.6, 4.8}; // C++98 STL vector<double> a2(4); // create vector with 4 elements // 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; // valid for array objects of same size // 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 " << &a3[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 " << &a3[2] << endl; cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl; cin.get(); return 0; }
-End-
2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/15121.html