c++ 常见问题之 vector 和数组


初始化vector 对象:

vector<T> v1  v1 为空vector
vector<T> v2(v1)  
vector<T> v2 = v1
vector<T> v3(n,val)
vector<T> v4(n)
vector<T> v5 {a,b,c..}
vector<T> v5 = {a,b,c..}

  vector<int> s(10,2) //10个元素每个元素是2

  vector<int> s{10,2}//2个元素 10和2

  vector操作:

v.empty()
v.size()
v.push_back()
v[n]
v1 == v2
v1 = {a,b,c}

 迭代器操作:

vector<int> r = {1,2,3,4,5,6};
vector<int>::iterator it;
for(it = r.begin();it!= r.end();it++)
    cout << *it << endl;

数组:

 数组a[d] d必须是常量表达式 unsigned cnt = 42; int a[cnt] //错误  string strs[get_size()] //错误,当get_size是 constexpr时正确

char a3[] = "c++";  a3的长度为4 还有空字符‘\0’

数组不允许将数组内容拷贝给其他数组作为初始值,也不能用数组为其他数组赋值

int a[] = {1,2,3};
int a2[] = a;//错误
a2 = a; //错误
int len = sizeof(a)/sizeof(a[0]);

复杂数组:默认情况类型修饰从右往左

int *ptr [10]; // ptr是含有10个int*的数组
 int &refs[10]; // 错误 不存在引用数组
 int (*parray)[10] = &arr; // parray 是个指针,指向大小为10的数组,数组中的类型为int
 int (&arrtest)[10] = arr; //arrtest 是个引用,引用类型为大小为10的数组,数组中的类型为int

递增

int j = 0,i;
i = ++j; // i=1,j=1
i = j++; // i=1,j=2

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM