[英]how can i access a vector of pointers pointing to other vectors? I tried the hackerrank program variable sized arrays in c++:
Consider an n-element array a, , where each index i in the array contains a reference to an array of k(i) integers (where the value of k(i) varies from array to array).考虑一个 n 元素数组 a, ,其中数组中的每个索引 i 都包含对 k(i) 整数数组的引用(其中 k(i) 的值因数组而异)。
Given a , you must answer q queries.给定 a ,您必须回答 q 查询。 Each query is in the format ij, where denotes an index in array a and j denotes an index in the array located at a[i].每个查询的格式为 ij,其中表示数组 a 中的索引,j 表示位于 a[i] 的数组中的索引。 For each query, find and print the value of element j in the array at location a[i] on a new line.对于每个查询,在位置 a[i] 处的数组中查找并在新行上打印元素 j 的值。
int n,q,k,input,r,s;
cin>>n>>q;
vector<int*> a;
vector<int> vec;
for(int i=0;i<n;i++)
{
cin>>k;
for(int j=0;j<k;j++)
{
cin>>input;
vec.push_back(input);
}
a.push_back(vec.data());
}
for(int m=0;m<q;m++)
{
cin>>r>>s;
cout<<endl<<*(a[r]+s);
}
The chief problem here is that each member of a
should point to a different array.这里的主要问题是a
每个成员都应该指向不同的数组。 That's at least what the exercise suggests.这至少是练习所暗示的。 You make all elements of a
point to the same vec
vector.您将a
点的所有元素都指向同一个vec
向量。
There's also the slight matter that vec.data()
keeps changing as it grows, but that's probably solved when you fix that first problem.还有一个小问题vec.data()
随着它的增长而不断变化,但是当您解决第一个问题时,这可能就解决了。
Note that in C++, we'd typically use a std::vector<std::vector<int>>
for this problem.请注意,在 C++ 中,我们通常会使用std::vector<std::vector<int>>
来解决这个问题。 The literal interpretation "each index i in the array contains a reference " wouldn't work because a C++ reference can't be a member of a vector, but the exercise does not appear to written with C++ in mind.字面解释“数组中的每个索引 i 都包含一个引用”是行不通的,因为 C++ 引用不能是向量的成员,但该练习似乎不是用 C++ 编写的。 Hence, "reference" does not mean C++ reference.因此,“引用”并不意味着 C++ 引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.