简体   繁体   English

C++:向量数组

[英]C++: array of vectors

I have an action that gets 5 vectors by reference:我有一个通过引用获取 5 个向量的操作:

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

I created inside the action an array of vectors vector<int> ve[] = {n, s, o, e, a};我在动作中创建了一个向量数组vector<int> ve[] = {n, s, o, e, a}; thinking they would be the same, but of course they are not... because after reading I find that ve[0] size is 5 and n size is 0.认为它们会相同,但当然它们不是......因为阅读后我发现 ve[0] 大小为 5,n 大小为 0。

How can I make an array of vectors but from the vectors given?我怎样才能从给定的向量中创建一个向量数组?

Thank you in advance先感谢您

#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;
}

This code creates an array of vectors which are copy constructed from the vectors which are referenced by the references passed as function arguments.这段代码创建了一个向量数组,这些向量是从作为函数参数传递的引用所引用的向量复制构造的。

Therefore, modifications of the vectors do not escape the function scope ... and you have the drawback of a copy.因此,向量的修改不会超出函数范围......而且你有一个副本的缺点。

Since you're using vector<int> & (a non-const reference) I assume you want these vectors to be "output" parameters.由于您使用的是vector<int> & (非常量引用),我假设您希望这些向量成为“输出”参数。 An array of references is not possible, but you can use std::reference_wrapper to circumvent this restriction:引用数组是不可能的,但您可以使用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!

I tried myself to figure it out我试着自己弄清楚

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;
}

This code works, the output is :此代码有效,输出为:

3/0
3/0

So it may be a mistake with your vectors initializations.因此,您的向量初始化可能是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM