我试图创建 N 个不同的 vector ,其中 N 是用户值(value)。
我试过这样的
for(int i=0;i<N;i++)
vector<int> v[i];
但是,当我尝试使用 vector 时,出现这样的错误
error: ‘v’ was not declared in this scope
我认为我创建的 vector 在该循环的范围内,我可能需要在外部声明它们,但如果我这样做,我如何迭代并创建 n 个不同的 vector ?
如何实现这个解决方案,能否实现?
有几点需要注意。
std::vector
有一个 push_back()
接受你的 vector 被定义为的方法。所以如果你做 vector<int>
然后 push_back(would_take_an_int_here)
.
您可以在此处阅读有关 vector 及其属性的信息:
http://en.cppreference.com/w/cpp/container/vector
就您正在寻找的内容而言,以上面的示例为例,让我们对其进行扩展。
所以你想要一个 vector 的 vector ?这意味着 push_back(needs_to_take_a_vector)
让我们从技术代码片段开始:
//First we define the vector
vector<int> x; //this is a vector of integers
vector<vector<int>> x; //this is a vector of integer vectors
//Now we want to let the user enter the amount of vectors needed.
//We would probably want a for-loop, because it is a count based loop and we
//know exactly how much the user wants to enter.
for(int i = 0; i < user_input; i++) {
vector<int> my_vec;
//This allows the vector<int> to be populated
//before being pushed back to x, not necessary though.
my_vec.push_back(i);
x.push_back(my_vec);
}
在循环之后我会尝试做一件巧妙的事情,只是为了看看你是否确实在你的 vector 中实现了你想要的,是这样的:
//notice there is a .size() function for vectors to see how many elements are
//inside the vector.
std::cout << "My user asked for " << user_input << " vectors, and my vectors size is " << my_vec.size() << " elements big" << endl;
我希望其中的一些内容能够解释某些部分,并超出您想要的范围,以便您能够理解!