Passing a 2 dimensional vector in Class OOP - c++

I am confused about passing a 2D vector using OOP
For example:
class ABC
{
public:
void function()
{
vector<vector<string>> high;
for ( int i=0; i<100; i++ )
{
high[0].push_back(i);
}
}
};
int main() {};
In the function , I do some calculations and the results are stored in 2D-array (high). I need the whole 2-d array to pass to the main function, How can i do it ?
I tried this,
class ABC{
public:
vector<vector<string>> function ()
{
vector<vector<string>> high;
for ( int i=0; i<100; i++ )
{
high[0].push_back(i);
}
}
};
int main()
{
ABC abc;
abc.function();
};
But it seems to be a total failure.
Thanks

You need to return your array from function like:
vector<vector<string>> function ()
{
vector<vector<string>> high;
high.resize(1); // <-- note this resize, because you are using high[0]
// element later
for ( int i=0; i<100; i++ )
{
high[0].push_back("some data...");
}
return high; // <-- note this return statement
}
Call function from main to get your data like this:
vector<vector<string>> data = function();
Other, but more efficient solution would be create your array in main and pass it by non-const reference to function:
class ABC{
public:
void function (vector<vector<string>>& high)
{
high.resize(1);
for ( int i=0; i<100; i++ )
{
high[0].push_back("some data...");
}
}
};
int main()
{
ABC abc;
vector<vector<string>> high;
abc.function(high);
};
Also make sure your vector contains elements you want to access. For example high[0] accesses first vector element. Use resize to change size. Note, that push_back automatically increases size.

for(int i = 0; i < 100; i++)
for(int j = 0; j < 100; j++)
//high[i].[j]
//high.at(i).at(j)
I Think something in this way.

Related

Merge Sorted array Error in c++: reference binding to null pointer of type 'int' (stl_vector.h)

https://leetcode.com/problems/merge-sorted-array/
In this leetcode question, this is the logic, I used
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = 0;
int j = 0;
int k = 0;
vector<int> ans;
while (i<m && j<n) {
if (nums1[i] < nums2[j]){
ans[k++] = nums1[i++];
}
else {
ans[k++] = nums2[j++];
}
}
while (i<m) {
ans[k++] = nums1[i++];
}
while (j<n) {
ans[k++] = nums2[j++];
}
for (int h = 0; h<(m+n); h++) {
nums1[h] = ans[h];
}
}
};
while running the code, I get this runtime error.
Error Image
How do I solve this
This is a vector of size zero
vector<int> ans;
This code attempts to change an element of the size zero vector.
ans[k++] = nums1[i++];
That's the cause of your error.
If you want to add an element to the end of a vector use push_back
ans.push_back(nums1[i++]);
C++ vectors don't change size automatically, you have to use push_back or resize or insert or something similar.
Alternatively make the vector the correct size to begin with
vector<int> ans(m + n);
though I prefer the push_back method myself.

How to set a matrix as a parameter to a function

I have an matris that the user will define it's size and it's elemant's value, i want to send it into a function from main as parameter or someway else, tried to use pointer for it but couldn't be successful, defining it as global is not a solution because the value i will give to matris' size is not set until the user enters. A matris can't be a functions parameter as well, so I'm stuck. Anyone can help me to send that matris to the function. - sorry for long question..
int main(){
int matris [k][k];
for(i=0 ; i<k ; i++){
for(t=0 ; t<k ; t++){
cin<<matris[i][t];
}
}
func(a,b,c,x);
}
func(int a, int b, int c, x){
//some stuff
}
That's in sum how the code looks like, i know using'x' like that is impossible, i am kinda trying to change the x with the matris value, but we are unable to set a matris as a parameter.
You can represent the matrix as a vector<vector<int> >. Try something like this:
#include <vector>
using namespace std;
void myFunction(const vector<vector<int> >& matrix) {
// do something w/ matrix passed in...
}
int main() {
// create a 3x4 matrix initialized to all zero
const size_t rowCount = 3;
const size_t colCount = 4;
vector<vector<int> > matrix(rowCount, vector<int>(colCount, 0));
// pass matrix to a function
myFunction(matrix);
return 0;
}
#include <iostream>
using namespace std;
int const k = 2;
void func( int (&m)[k][k] )
{
//some stuff
cout << "func!\n";
}
int main()
{
int matris[k][k];
for(int i=0 ; i<k ; i++)
{
for(int t=0 ; t<k ; t++)
{
//cin >> matris[i][t];
}
}
func( matris );
}

Declaring an array of pointers to objects dynamically in C++

I have to declare an array of pointers to objects (of classes) in C++. I thought this was the only way, but apparently I was wrong, as it throws a syntax error when I try to compile it. Specifically, among the 7 errors I received, 2 of these errors are in the lines: where I create the array using "new", and in the line where I call the "setData()" function. Can you tell me where I went wrong? Thanks.
#include <iostream>
class Test
{
public:
int x;
Test() { x=0; }
void setData(int n) { x=n; }
};
void main()
{
int n;
Test **a;
cin >> n;
a=new *Test[n];
for(int i=0; i<n; i++)
{
*(a+i)=new Test();
*(a+i)->setData(i*3);
}
}
Use a=new Test*[n];
Other than that, you have no deleteĀ“s in your program, trivial getter/setters
for public variables are strange, and *(a+i) could be a[i]
Your syntax is close but slightly off. Use this instead:
Test **a;
...
a=new Test*[n];
for(int i=0; i<n; i++)
{
a[i]=new Test();
a[i]->setData(i*3);
}
...
// don't forget to free the memory when finished...
for(int i=0; i<n; i++)
{
delete a[i];
}
delete[] a;
Since you are using C++, you should use std::vector instead. I would also suggest passing the desired value to the class constructor:
#include <iostream>
#include <vector>
class Test
{
public:
int x;
Test(int n = 0) : x(n) { }
Test(const Test &t) : x(t.x) { }
void setData(int n) { x=n; }
};
int main()
{
int n;
std::vector<Test> a;
cin >> n;
a.reserve(n);
for(int i=0; i<n; i++)
{
a.push_back(Test(i*3));
}
...
// memory is freed automatically when finished...
return 0;
}

Can't fill the array that is a member of a class. C++

#include <iostream>
using namespace std;
class SomeClass {
public:
bool someArray[4][4]={{0,0,0,0},{0,0,0,0}};
};
int main()
{
SomeClass super;
super.someArray={{1,1,1,0},{1,0,0,1}}; //This goes red, indicates a mistake. How do i properly fill it?
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
Please see the comments in the code above.
By the way: super.someArray[4][4]={{1,1,1,0},{1,0,0,1}}; doesn't work either and it probably shouldn't.
You probably mean to use bool someArray[2][4] (i.e, an array with two elements that contains arrays with four boolean elements).
You can't assign one array into another in C++; you'll need to copy the individual elements. I.e., something like:
super.someArray[0][0] = 1;
super.someArray[0][1] = 1;
super.someArray[0][2] = 1;
super.someArray[0][3] = 0;
super.someArray[1][0] = 1;
super.someArray[1][1] = 0;
super.someArray[1][2] = 0;
super.someArray[1][3] = 1;
(If you have some source for your data, you could use a loop of course.)
The following worked for me using the GNU compiler. Notice that I replaced your raw array with std::tr1::array. This class is more flexible with respect to assigning entire arrays (as opposed to just initializing arrays from literals).
#include <iostream>
#include <tr1/array>
using namespace std;
using namespace tr1;
typedef array<array<bool,4>,4> array4x4;
class SomeClass {
public:
array4x4 someArray;
SomeClass() : someArray((array4x4){{{{0,0,0,0}},{{0,0,0,0}}}}) {}
};
int main()
{
SomeClass super;
super.someArray=(array4x4){{{{1,1,1,0}},{{1,0,0,1}}}}; //Now works
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
However, the following approach is a bit closer to where you started, and demonstrates some of the things suggested in other comments...
#include <iostream>
#include <algorithm>
using namespace std;
class SomeClass {
public:
bool someArray[4][4];
SomeClass()
{
bool temp[4][4] = {{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
for ( int j=0; j<4; j++ ) for ( int i=0; i<4; i++ ) someArray[j][i] = temp[j][i];
}
};
int main()
{
SomeClass super;
bool temp[4][4] = {{1,1,1,0},{1,0,0,1}}; // a local source of data
for ( int j=0; j<4; j++ ) for ( int i=0; i<4; i++ ) super.someArray[j][i] = temp[j][i];
for (int i=0;i<4;i++){
for (int j=0;j<4;j++){
cout<<super.someArray[i][j];
}
cout<<endl;
}
return 0;
}
super.someArray[4][4]={{1,1,1,0},{1,0,0,1}};
The line above just needs to be:
super.someArray[4][4]={1,1,1,0,1,0,0,1};
Explaination:
it will automatically go the next section of the array. If you think of it as a table, once the first row is filled up, it will start declaring it for the next row.
So if you wrote:
super.someArray[4][4]={1,1,1,1,1};
it would set:
someArray[0][0]
someArray[0][1]
someArray[0][2]
someArray[0][3]
someArray[1][0]
all equal to 1.
(I might have the numbers switched so it could be x and y places are changed, I can't recall for c++)

c++ using "indexing" over a 2D matrix, under this structure

don't know why but i get an error: after this structure i can't index the matrix, so i cant use the "indexing method" over the defined matrix.Can anyone tell me why? or how to fix it?
Header:
const int days=31;
const int exp=6;
struct Array{
int days;
int exp;
int **M;
};
Constuctor:
void constr(Array loc){
//Construct of 31*6 Matrix, were 31 nr. of days and 6 specific types:
//0-HouseKeeping, 1-Food, 2-Transport, 3-Clothing, 4-TelNet, 5-others
loc.days = days;
loc.exp = exp;
loc.M = new int*[loc.days];
for(int i=0; i<loc.days;i++ ){
loc.M[i] = new int[loc.exp];
for (int j = 0; j< loc.exp; j++){
loc.M[i][j] = 0;
}
}
}
Controller.cpp
void add(int cant,int tip, Array M){
//Adds to current day the amount to a specific type
currDay();
M[currentDay][tip] += cant; ////////////error
}
void insert(int zi,int tip,int cant, Array M){
//Adds to current day the amount to a specific type
M[zi][tip] = cant; ///////////error
}
void removeDay(int day, Array M){
for(int i = 0; i<6; i++)
M[day][i] = 0; ///////////error
//zi and tip ~ day type... for easier read.
//i need to manage the expenses of a family in a month doesn't matter which
ERROR: error: no match for 'operator[]'
UI(where constructor is used):
int main(){
Array M;
constr(M);
printMenu();
return 0;
}
You're not accessing the member:
M.M[currentDay][tip]
instead of
M[currentDay][tip]
Or you could define operator [] for your struct:
struct Array{
int days;
int exp;
int **M;
int*& operator[] (int idx) { return M[idx]; }
};
You are trying to call operator[] on the type array. You need to get the pointer member first.
M.M[day][i];
That said: You are not writing C++ but some obscure form of bad C. You might want to have a look at the book list and read one of them before pursuing coding any further.
You have at least two problems:
The first is that you are using the actual structure as the array, which wont work. Use e.g. M.M[day][i].
The second is that when you create the array, you pass the structure by value, this means it will be copied to a local variable in the constr function and the data will not be available in the function calling constr. Pass it as a reference instead, i.e. void constr(Array &loc).
The second problem can also be solved by using a constructor in the structure, instead of a separate function:
const int DAYS=31;
const int EXP=6;
struct Array{
int days;
int exp;
int **M;
// Constructor, called when an instance of structure/class is created
Array(){
days = DAYS;
exp = EXP;
M = new int*[days];
for(int i=0; i<days;i++ ){
M[i] = new int[exp];
for (int j = 0; j< exp; j++){
M[i][j] = 0;
}
}
}
// Destructor, called when structure/class is destroyed
~Array(){
if(M){
for(int i=0;i<days;i++){
if(M[i])
delete [] M[i];
}
delete [] M
}
}
// Copy constructor, called when instance of structure/class is copied
Array(const Array &array){
days = array.days;
exp = array.exp;
M = new int*[days];
for(int i=0; i<days;i++ ){
M[i] = new int[exp];
for (int j = 0; j< exp; j++){
M[i][j] = array.M[i][j];
}
}
}
};