1

I have an action that gets 5 vectors by reference:

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

How can I make an array of vectors but from the vectors given?

Thank you in advance

Laura Galera
  • 89
  • 1
  • 10

2 Answers2

2
#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. An array of references is not possible, but you can use std::reference_wrapper to circumvent this restriction:

#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!
Daniel Jour
  • 15,896
  • 2
  • 36
  • 63
1

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.

Lucas Gras
  • 961
  • 1
  • 7
  • 22
  • 1
    @Lucas Gras That is because you didn't try to modify either vector after affectation. The vectors are copy-constructed into `ve`. – Storm Dec 27 '19 at 15:00