C++:向量数组

C++: array of vectors

本文关键字:数组 向量 C++      更新时间:2023-10-16

我有一个通过引用获得 5 个向量的操作:

void ReadFromFile(string nomFitxer, vector<int> &n, vector<int> &s, vector<int> &o, vector<int> &e, vector<int> &a){

我在动作中创建了一个向量数组,vector<int> ve[] = {n, s, o, e, a};认为它们是相同的,但当然它们不是......因为阅读后我发现 ve[0] 大小为 5,n 大小为 0。

我怎样才能从给定的向量中制作一个向量数组?

提前谢谢你

#include <vector>
#include <iostream>
using std::vector;
void foo(vector<int> & a, vector<int> & b) {
vector<int> vectors[] = {a, b};
std::cout << "vectors[0].size() = " << vectors[0].size() << std::endl;
vectors[0][0] = 42;
std::cout << "vectors[0][0] = " << vectors[0][0] << std::endl;
}
int main() {
vector<int> one = {1, 2, 3, 4};
vector<int> two = {11, 12, 13, 14};
std::cout << "one[0] = " << one[0] << std::endl;
foo(one, two);
std::cout << "one[0] = " << one[0] << std::endl;
}

此代码创建一个向量数组,这些向量是从作为函数参数传递的引用的向量复制构造的。

因此,向量的修改不会逃脱函数范围......而且你有副本的缺点。

由于您使用的是vector<int> &(非常量引用(,我假设您希望这些向量成为"输出"参数。引用数组是不可能的,但您可以使用std::reference_wrapper来规避此限制:

#include <functional>
void bar(vector<int> & a, vector<int> & b) {
using vref = std::reference_wrapper<vector<int>>;
vref vectors[] = {a, b};
std::cout << "vectors[0].size() = " << vectors[0].get().size() << std::endl;
vectors[0].get()[0] = 42;
std::cout << "vectors[0][0] = " << vectors[0].get()[0] << std::endl;
}
// Now use bar instead of foo with the above main function!

我试着弄清楚

void foo(std::vector<int> &a, std::vector<int> &b)
{
std::vector<int> ve[] = {a, b};
std::cout << ve[0].size() << "/" << ve[1].size() << std::endl;
std::cout << a.size() << "/" << b.size() << std::endl;
}
int main()
{
std::vector<int> a = {0, 1, 2};
std::vector<int> b = {};
foo(a, b);
return 0;
}

此代码有效,输出为:

3/0
3/0

因此,这可能是向量初始化的错误。