C++ 创建一个 vector 大小的数组,然后将 vector 复制到 C 样式数组中

标签 c++ c++11 visual-c++

<分区>

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++;
    }
}

关于C++ 创建一个 vector 大小的数组,然后将 vector 复制到 C 样式数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53313808/

相关文章:

c++ - 使用结构作为映射中的键

c++ - 为什么我们需要创建一个单参数构造函数才能使用临时无名对象?

c++ - 如何在我的 C++ 项目中包含 *.cpp 文件?

c++ - : list<object *> and list<object &> 之间的差异

.net - 如何在 Visual C++ .net 中将一个项目从一个列表框转移到另一个

c++ - 错误 C3867 : Functional call missing argument

c++ - 多态性是否适用于值?或者在按(基)值返回时使用派生类的 move 构造函数

c++ - 具有类型/非类型参数的相同模板类?

c++ - 为什么initializer_list没有违反 "One Class-Type Conversion"的规则

visual-c++ - TaskDialog 在 Visual C++ 中始终位于顶部