[英]How do I get the values of an array to a vector then back to another array?
Dynamic array in Stack? 堆栈中的动态数组? So from this link, I saw this:
所以从这个链接,我看到了这个:
#include <iostream>
#include <vector>
int main()
{
int x = 0;
std::cin >> x;
std::vector<char> pz(x);
}
But what I want is something like this:但我想要的是这样的:
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;
}
So any suggestions on doing this?那么有什么建议吗?
Here's what I originally did which isn't allowed in C++:这是我最初做的,在 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;
}
If you modify generate_random_vector
to return an std::vector<long int>
, and define another_p
and arrayName
as std::vector<long int>
as well (default constructed, no need to specify size) then you can simply use assignment, as I said in my comment:如果您修改
generate_random_vector
以返回std::vector<long int>
,并将another_p
和arrayName
定义为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.