1

I want to pass a variable which is of type vector<vector<char>> p into another function declared as void foo(vector<vector<char>> &var). To pass p into foo I simply did foo(p). While doing so I get the following error

error: no match for call to ‘(std::vector<std::vector<char> >) (std::vector<std::vector<char> >&)’

I have followed the discussion given in here!

Update

Now I get a Segmentation fault (core dumped) error. I am attaching a simpler version of the code below.

#include <iostream>
#include <vector>
using namespace std;

class foo{
  private:
    vector<vector<char>> b;
  public:
    foo(vector<vector<char>> &n){
      vector<vector<char>> b(n);
    }
    void print_foo() {
      for (int i = 0; i < b.size(); i++) {
          for (int j = 0; j < b[i].size(); j++) {
            cout << b[i][j];
          }
          cout << endl;
      }
    }
};

int main(int argc, char** argv) {
  char pp[4][4] = {
    {'1', '1', '1', '1'},
    {'1', '0', '0', '0'},
    {'1', '0', '0', '0'},
    {'1', '0', '0', '1'},
  };

  vector<vector<char>> p;
  for(int i = 0; i < 4; i++) {
    vector<char> m_row;
    for (int j = 0; j < 4; j++) {
      m_row.push_back(p[i][j]);
    }
    p.push_back(m_row);
  }

  foo a(p);
  a.print_foo();
}
Geek
  • 395
  • 1
  • 9

1 Answers1

3

The issue is this line:

m_row.push_back(p[i][j]);

You have mistyped pp as p.

Instead, use this:

m_row.push_back(pp[i][j]);

According to current code, it won't print the matrix correctly. Why? Because of this:

foo(vector<vector<char>> &n) {
    vector<vector<char>> b(n);
}

This code creates a local object b which will die after it goes out of scope.

foo(vector<vector<char>> &n) {
    vector<vector<char>> b(n); // local object created
} // b dies here

Instead, you must do this:

foo(vector<vector<char>> &n): b(n) {
}

Final Code:

#include <iostream>
#include <vector>
using namespace std;

class foo{
  private:
    vector<vector<char>> b;
  public:
    foo(vector<vector<char>> &n): b(n) { }
    void print_foo() {
      for (int i = 0; i < b.size(); i++) {
          for (int j = 0; j < b[i].size(); j++) {
            cout << b[i][j];
          }
          cout << endl;
      }
    }
};

int main(int argc, char** argv) {
  char pp[4][4] = {
    {'1', '1', '1', '1'},
    {'1', '0', '0', '0'},
    {'1', '0', '0', '0'},
    {'1', '0', '0', '1'},
  };

  vector<vector<char>> p;
  for(int i = 0; i < 4; i++) {
    vector<char> m_row;
    for (int j = 0; j < 4; j++) {
      m_row.push_back(pp[i][j]);
    }
    p.push_back(m_row);
  }

  foo a(p);
  a.print_foo();
}
Kunal Puri
  • 3,419
  • 1
  • 10
  • 22
  • 3
    And this is yet another example why one should use meaningful names for their variables. – Fureeish Feb 17 '19 at 00:02
  • Doing `b =n` does not print anything either. When I check `b.size()` it prints `0`. Any idea why? – Geek Feb 17 '19 at 00:08