VS2013关于C++ Primer5 的3.42题报错

练习3.42:编写一段程序,将含有整数元素的数组的vector对象拷贝给一个整型数组。

#include<iostream>
#include<vector>
using namespace std;

int main()
{
	vector<int> v;
	const int sz = 10; //常量sz作为vector对象的容量


	srand((unsigned)time(NULL));//产生随机数种子
	//产生0-100的随机数,给vector赋值,并打印出来
	for (int i = 0; i != sz; i++){
		v.push_back(rand() % 100);
		cout << v[i] << " ";
	}
	cout << endl;



	auto it = v.cbegin();
	int num[10];//int num[v.size()];
	//给数组逐个元素赋值,将vector对象内容拷贝到数组中
	for (auto &val : num){
		val = *it;
		cout << val << " ";
		it++;
	}
	cout << endl;


	system("pause");
	return 0;
}

注意:

如果使用 int num[v.size()]; 这句代码替换int num[10];,编译器会报错,因为数组长度即[]中的内容应该是一个字面值常量。

不是所有的编译器都支持 int f[n];
但是gcc新版本的确可以这么写,不能说这么写就是错的。

所以你可能看见有的书上或者网站上这么写,而你的编译器不支持而已。

posted on 2019-12-17 15:45  丁错儿  阅读(2)  评论(0编辑  收藏  举报

导航