繁体   English   中英

如何将数组的值获取到向量然后返回到另一个数组?

[英]How do I get the values of an array to a vector then back to another array?

堆栈中的动态数组? 所以从这个链接,我看到了这个:

#include <iostream>
#include <vector>

int main()
{
    int x = 0;
    std::cin >> x;

    std::vector<char> pz(x);
}

但我想要的是这样的:

include <iostream>
include <vector>

using namespace std;

int main()
{
     long int *p;
     long int *another_p;
     p = generate_random_vector(); //this is a function that generates a vector
                                   //and I'm assigning this vector to *p

     vector<long int>vectorName(n); //size n will be known when I read from a file
                                    //I would like to store the value of vector of *p in vectorName

     *another_p = vectorName; //I would like to store the value of vectorName in *another_p

     return 0;
}

那么有什么建议吗?

这是我最初做的,在 C++ 中是不允许的:

int main()
{
     long int *p;
     long int *another_p;
     long int arrayName[n]; //n can be obtained from reading a file

     p = generate_random_vector(); 

     for ( int i = 0; i < n; i++ )
     {
          arrayName[i] = p[i];
     }

     for ( int i = 0; i < n; i++ )
     {
          another_p[i] = arrayName[i];
     }
     return 0;
}

如果您修改generate_random_vector以返回std::vector<long int> ,并将another_parrayName定义为std::vector<long int> (默认构造,无需指定大小),那么您可以简单地使用赋值,如我在评论中说:

std::vector<long> generate_random_vector();

int main()
{
     std::vector<long> p;
     std::vector<long> another_p;
     std::vector<long> arrayName;

     p = generate_random_vector(); 

     arrayName = p;
     another_p = arrayName;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM