[英]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_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.