VC++ 在下面的代码中给出错误:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> a;
a.push_back(10);
a.push_back(20);
a.push_back(30);
int arr[a.size()];
std::copy(a.begin(), a.end(), arr);
for(int index = 0 ; index < a.size(); index++)
{
std::cout << " The value is " << arr[index] << std::endl;
}
}
它在整数数组声明处出错,指出变量“a”的值不能用作常量?
我们如何解决我的目标是将 vector 的内容传输到“C”样式数组的问题?
此错误取决于编译器。 C++ 要求数组定义中有常量。一些编译器提供了一个扩展,有助于在声明 Array 时使用非常量。我在 Xcode 10 (GCC) 上成功编译了您的代码。
对于您的编译器,您可以简单地添加 int *arrPtr = a.data();
以获得给定数组的 c 风格数组指针。
int main()
{
std::vector<int> a;
a.push_back(10);
a.push_back(20);
a.push_back(30);
//int arr[a.size()];
//std::copy(a.begin(), a.end(), arr);
//for(int index = 0 ; index < a.size(); index++)
//{
// std::cout << " The value is " << arr[index] << std::endl;
//}
int *arrPtr = a.data();
for(int index = 0 ; index < a.size(); index++)
std::cout<< " The value is " << arrPtr[index] << std::endl;
for(int index = 0 ; index < a.size(); index++)
{
std::cout<< " The value is " << *arrPtr << std::endl;
arrPtr++;
}
}