C ++创建一个矢量大小的数组,然后将矢量复制到C样式数组[复制]

问题描述 投票:1回答:2

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++ c++11 visual-c++
2个回答
-2
投票

编译器告诉你的是,a.size()不是compile time常量吗?因此,你不能像这样声明数组。你需要调用int *arr = new int[a.size()];然后删除它。


3
投票

此错误取决于编译器。 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++;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.