代码之家  ›  专栏  ›  技术社区  ›  Programmer

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

  •  1
  • Programmer  · 技术社区  · 7 年前

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

    它在整数数组声明中出错,声明变量的值为 '不能用作常量?

    C

    2 回复  |  直到 7 年前
        1
  •  -2
  •   Rizwan    7 年前

    编译器告诉你的是 a.size() compile time 常数因此,不能像这样声明数组。你需要打电话 int *arr = new int[a.size()];

        2
  •  3
  •   Rizwan    7 年前

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