I'm having problems with code I'm writing to solve give mazes using class Templates and stacks. The algorithm worked well enough before I implemented code to be able to read mazes from files. Now it doesn't solve the maze, it only outputs "Stack is full! Can not push" and prints the maze. The algorithm I'm adhering goes like:
Define the two-dimensional int array M as given
above, and two int stacks which will store the row
and column index of the locations we have checked.
Search the array M to locate the entry 2 to find your
starting point
Push the current location (i.e., the row and column
index) onto the () stacks.
Check if the value stored at the current location is
a 3; if it is, we are done. If not, set it to 2.
Check the current location's four neighbours in order (e.g., clockwise from north). If any is a 1 or a
3, pop that location onto the stack and move there
next.
If none of the neighbours store a 1, we are at a
dead-end: set the value at that location to 0, and
pop the new location from the stack.
Any help is appreciated!
#include <iostream>
#include <fstream>
#include <string>
#define MAX_STACK 10
void PrintMaze(int **Maze, int M, int N);
template <class T>
class MyStack {
private:
T *contents;
int top, maxsize;
public:
~MyStack(void);
MyStack (void);
MyStack (unsigned int StackSize);
bool checkEmpty(void);
bool checkFull(void);
void push(T c);
T pop(void );
int scon(void);
};
template <class T> MyStack<T>::~MyStack(void)
{
delete [] contents;
}
template <class T> MyStack<T>::MyStack(void)
{
top=0;
contents = new T [MAX_STACK];
maxsize = MAX_STACK;
}
template <class T> MyStack<T>::MyStack(unsigned int StackSize)
{
top=0;
maxsize = StackSize;
contents = new T[StackSize];
}
template <class T> bool MyStack<T>::checkEmpty(void)
{
return MAX_STACK == 0;
}
template <class T> bool MyStack<T>::checkFull(void)
{
return MAX_STACK == 10;
}
template <class T> void MyStack<T>::push(T c)
{
if(checkFull())
{
std::cout << "Stack is fulL! Can not push" << std::endl;
}
else
{
contents[top]=c;
top++;
}
}
template <class T> T MyStack<T>::pop(void)
{
top--;
return(contents[top]);
if(checkEmpty())
{
std::cout << "Stack empty! Can not pop" << std::endl;
return 0;
}
else
{
top--;
return(contents[top]);
}
}
template <class T> int MyStack<T>::scon(void)
{
return(*contents);
}
int main(void )
{
// Open the file
std::ifstream InFile;
InFile.open("C:/Users/Desktop/Computer Science/Maze6.txt");
if (InFile.fail())
{
std::cerr << "Error - cannot open Maze.txt" << std::endl;
return(1);
}
// Read the size of the maze
int Rows, Cols;
InFile >> Rows >> Cols;
std::cout << "The maze has " << Rows << " rows and " << Cols << " columns." << std::endl;
// Dynamically assign memory for the array
int **M = new int*[Rows];
for(int i = 0; i < Rows; ++i)
{
M[i] = new int[Cols];
}
/// Read in the data
for (int i=0; i<Rows; i++)
for (int j=0; j<Cols; j++)
{
char c;
InFile >> c;
M[i][j] = (int)(c-'0');
}
// Display the maze
std::cout << "Here is the maze: ";
PrintMaze(M, Rows, Cols);
//////////////////////////////
MyStack<int> s1;
MyStack<int> s2;
for(int Rows=0; Rows<sizeof(M); Rows++)
{
for(int Cols=0; Cols<sizeof(M); Cols++)
{
if(M[Rows][Cols] == 2)
{
s1.push(Rows);
s2.push(Cols);
if(Rows-1 == 1)
{
s1.push(Rows-1);
s2.push(Cols-1);
M[Rows-1][Cols] == 2;
}
if(Cols+1 == 1)
{
s1.push(Rows);
s2.push(Cols+1);
M[Rows][Cols+1] == 2;
}
if(Rows+1 == 1)
{
s1.push(Rows+1);
s2.push(Cols);
M[Rows-1][Cols] == 2;
}
if(Cols-1 == 1)
{
s1.push(Rows);
s2.push(Cols-1);
M[Rows][Cols-1] == 2;
}
else
{
M[Rows][Cols] = 0;
s1.pop();
s2.pop();
}
}
if(M[Rows][Cols] == 3)
{
std::cout << "Maze completed! Item found at row: " << Rows << " column: " << Cols << std::endl;
std::cout << "Column path: " << s2.scon() << std::endl;
std::cout << "Row path: " << s1.scon() << std::endl;
}
else
{
M[Rows][Cols] == 2;
}
}
}
//////////////////////////////
// Deallocate memory
for(int i =0; i<6; i++)
{
for(int j = 0; j<6; j++)
{
std::cout <<M[i][j] << ' ';
}
std::cout << std::endl;
}
return (0);
}
void PrintMaze(int **Maze, int M, int N)
{
std::cout << std::endl;
for(int i = 0; i<M; i++)
{
for(int j=0; j<N; j++)
{
std::cout << Maze[i][j];
}
std::cout << std::endl;
}
}
sizeof(M) is wrong, it will give you the size of the pointer M itself, not the size of what it points to. You need to explicitly use the Rows and Cols variables, using their original values, and use different values for iterating over the rows and the columns.
As in
//////////////////////////////
MyStack<int> s1;
MyStack<int> s2;
for(int i=0; i<Rows; i++)
{
for(int j=0; j<Cols; j++)
{
// Use i and j as indexes...
}
}
Related
I am attempting to create a function that returns a vector as an answer, ie [1,3]. I am confused about the process of manipulating that information once the function has been called. Should I set it equal to a new vector? How would I then display the contents of this new vector? Here is my code for reference. When I attempt to set the function call to a new vector and display it, I get an out of bounds error.
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
vector<int> twoNumberSum(vector<int> array, int targetSum);
int main()
{
int tSum = 10;
vector<int> test{3,5,-4,8,11,1,-1,6};
twoNumberSum(test,tSum);
}
//O^2 complexity
//Two number Sum
vector<int> twoNumberSum(vector<int> array, int targetSum)
{
for (int i=0; i<array.size() -1; i++)
{
int firstNum = array[i];
for(int j=i+1;i<array.size();i++)
{
int secondNum = array[j];
if(firstNum + secondNum == targetSum)
{
return vector<int>{firstNum,secondNum};
}
}
}
return {};
}
To print vector, you could use something like this:
void printVector(vector<int> v) {
cout << "{";
for(int item : v) {
cout << item << ", ";
}
cout << "}";
}
And use it as in a main function: print_vector(twoNumberSum(test, tSum));
Now, bug.
for(int j=i+1;i<array.size();i++)
You increase and check the value of variable i, but you need to use j there.
That will be correct: for(int j=i+1;j<array.size();j++)
The program works correctly and prints the result of function to the console:
void print_vector(vector<int> v);
vector<int> twoNumberSum(vector<int> array, int targetSum);
int main()
{
int tSum = 10;
vector<int> test{3,5,-4,8,11,1,-1,6};
print_vector(twoNumberSum(test, tSum));
}
vector<int> twoNumberSum(vector<int> array, int targetSum)
{
for (int i=0; i<array.size() -1; i++)
{
int firstNum = array[i];
for(int j=i+1;j<array.size();j++)
{
int secondNum = array[j];
if(firstNum + secondNum == targetSum)
{
return vector<int>{firstNum,secondNum};
}
}
}
return {};
}
void print_vector(vector<int> v) {
cout << "{";
for(int item : v) {
cout << item << ", ";
}
cout << "}";
}
I have a problem with my C++ code. I need to make the sum of the vectors component by component. For example, if I have A(2,1) and B(3,3) the result should be (5,4). I tried to do something but apparently I have a problem and I don't know what to do. The error is: ,,No member called push in std::_1vector" My code is:
#include <iostream>
#include "stack_base.h"
#include <vector>
using namespace std;
template<typename T>
class App {
public:
Stack<T> * stack;
App(Stack<T> &stack) {
this->stack = &stack;
}
T sum(){
Stack<T> *tempStack = stack;
T sum=0;
int size = stack->getTopLevel();
for(int i=0; i<=size; i++) {
sum+=tempStack->peek();
tempStack->pop();
}
return sum;
}
T substract(){
Stack<T> tempStack = *stack;
T substr=0;
for(int i=0; i<=stack->getTopLevel(); i++) {
substr-=tempStack.peek();
tempStack.pop();
}
return substr;
}
};
void display(vector<int> &v)
{
for(int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
cout << "\n" << endl;
}
int main(){
using namespace std;
Stack<int> myStack;
App<int> a(myStack);
unsigned int i = 0;
std::vector<int> v1;
std::vector<int> v2;
// Populate v1 and v2 here
// Check that v1 and v2 have the same length
if (v1.size() != v2.size())
{
// error here
}
std::vector<int> v3; // This will hold the resulting vector
// Preallocate the necessary memory if you like here, but it
// isn't necessary and doesn't gain you much.
for (auto i = 0ul; i < v1.size(); ++i)
{
v3.push_back(v1[i] + v2[i]);
}
int x;
cout << "Enter five integer values for v1" << endl;
for(int i; i<5; i++)
{
cin >> x;
v1.push_back(x);
}
cout << "Enter five integer values for v2" << endl;
for(int i; i<5; i++)
{
cin >> x;
v2.push_back(x);
}
cout << "Size of Vector= " << v2.size() << endl;
display(v3);
return 0;
}
This is Stack:
#include <iostream>
using namespace std;
#define NMAX 30 // pre-processing directive
template<typename T>
class Stack {
private:
// an array of NMAX dimension
T stackArray[NMAX];
/* the top of the stack, representing the INDEX of last element of the
stackArray:0, 1, 2,....*/
int topLevel;
public:
void push(T x) {
//puts an element in the stack array
//check if the stack array has the maximum dimension
if (topLevel >= NMAX - 1)
{
cout<<"The stack is full: we have already NMAX elements!\n";
//exit the function without making anything
return;
}
/*add an element=> the index of the last element of the stack Array
increases and put the value of the new element in the stack array*/
stackArray[++topLevel] = x;
}
int isEmpty() {
//returns 1, if topLevel>=0, meaning the stack array has elements
// returns 0, otherwise
return (topLevel < 0);
}
T pop() {
// extracts and element from the stack array and returns the new top
if (isEmpty()) {
// the extraction is made only if the array is not empty
cout<<"The stack is empty! \n";
T x;
return x;
}
// the topLevel decreases and the new top is changed
return stackArray[--topLevel];
}
T peek() {
// returns the top of the stack
if (isEmpty()) {
// the extraction is made only if the array is not empty
cout<<"The stack is empty! \n";
T x;
return x;
}
return stackArray[topLevel];
}
void display(){
for(int i=0;i<=topLevel;i++)
cout<<stackArray[i];
}
bool search(T num){
for(int i=0; i<=topLevel;i++)
if(num==stackArray[i])
return true;
return false;
}
int getTopLevel(){
return topLevel;
}
Stack() { // constructor
topLevel = -1; // the stack is empty in the beginning
}
void sort(T s){
if (!isEmpty()) {
T x = Pop(s);
sort(s);
push(s, x);
}
}
~Stack() { // destructor
}
};
You are never adding any elements to your vector. In the preceding three lines, you attempt to access elements that do not exist, but the vectors only do bounds checking if you call the 'at' method instead of using the bracket notation. What are you trying to accomplish in that for-loop?
To add two vectors of the same length pair-wise, which is what I think you want, you can do this:
std::vector<int> v1;
std::vector<int> v2;
// Populate v1 and v2 here
// Check that v1 and v2 have the same length
if (v1.size() != v2.size())
{
// error here
}
std::vector<int> v3; // This will hold the resulting vector
// Preallocate the necessary memory if you like here, but it
// isn't necessary and doesn't gain you much.
for (auto i = 0ul; i < v1.size(); ++i)
{
v3.push_back(v1[i] + v2[i]);
// Debugging statement
std::cout << "Added " << v1[i] << " and " << v2[i] << " to get " << v3[i] << " for index " << i << std::endl;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, this is just few methods from my myArray.cpp class. It gives me error on
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
these above code(error - which is non-class type double). can anyone please help me? I'm trying to copy an array to the object array
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
}
void myArray::setSize(int value) {
if (value > 0) {
size = value;
}
}
void myArray::setData(int index, double value) {
if ((index >= 0) && (index < size)) {
arr[index] = value;
} else {
// cout << "NO!" << endl;
}
}
double myArray::getData(int index) const {
if ((index >= 0) && (index < size)) {
return arr[index];
} else {
return arr[size - 1];
}
}
That's my main.cpp class
#include <iostream>
#include "myArray.h"
//#include "myArray.cpp"
using namespace std;
int main (int argc, char **argv)
{
cout << "**************Testing Default Constructor*****************" << endl;
myArray A1;
cout << "A1: ";
A1.print();
cout << "**************Testing Alt Constructor 1*****************" << endl;
myArray A2(5,0);
cout << "A2: ";
A2.print();
cout << "**************Testing init*****************" << endl;
A2.init();
cout << "A2 after init: ";
A2.print();
int size = 5;
double *temp = new double[size];
for(int i = 0; i < size; i++)
{
temp[i] = i;
}
cout << "**************Testing Alt Constructor 2*****************" << endl;
myArray A3(temp, size);
cout << "A3: ";
cout << A3.getSize();
cout << endl;
cout << "Fe";
A3.print();
That's my myArray.cpp class
#ifndef MYARRAY_H_INCLUDED
#define MYARRAY_H_INCLUDED
/***************************************************************************
* myArray class header file
***************************************************************************/
class myArray
{
public:
myArray();
myArray(int,double);
myArray(double*, int);
~myArray();
int getSize() const;
bool equal(const myArray &rhs) const;
void setData(int index, double value);
void insert(int, double);
void remove(int);
double get(int);
void clear();
int find(double);
bool equals(myArray&);
void print() const;
void init();
double getData(int index) const;
// void init();
// void print() const;
void expand();
private:
int size;
double *arr;
void setSize(int value);
};
#endif // MYARRAY_H_INCLUDED
That's my myArray.cpp class where I'm getting the error in the default paramaterized constructor
#include "myArray.h"
#include <iostream>
using namespace std;
myArray::myArray() : size(0) {
// size = 10;
arr = new double [size];
}
/*myArray::myArray(int _size) : size(_size) {
// size = _size;
arr = new double [size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
} */
myArray::myArray(int _size, double value) : size(_size) {
// size = _size;
arr = new double [size];
for (int i = 0; i < size; i++) {
arr[i] = value;
}
}
/*myArray::myArray(myArray* temp, int size)
{
setSize(temp.getSize());
for (int i = 0; i < getSize(); i++) {
setData(i, temp.getData(i));
}
} */
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
//double arr[size];
// arr = new double[size];
// p = orig;
// for(int i = 0;i<size;i++)
// {
// arr[i] = orig[i];
// cout << arr[i] << " ";
// }
// cout << endl;
// setSize(size);
// for (int i = 0; i < getSize(); i++)
// setData(i, orig.getData(i));
// cout << "hell";
// for (int i = 0; i < size; i++) {
// arr[i] = myArray[i];
// cout << arr[i];
//}
// arr = myArray;
}
myArray::~myArray() {
delete [] arr;
}
int myArray::getSize() const {
return size;
}
void myArray::setSize(int value) {
if (value > 0) {
size = value;
}
}
void myArray::setData(int index, double value) {
if ((index >= 0) && (index < size)) {
arr[index] = value;
} else {
// cout << "NO!" << endl;
}
}
double myArray::getData(int index) const {
if ((index >= 0) && (index < size)) {
return arr[index];
} else {
return arr[size - 1];
}
}
void myArray::print() const {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void myArray::expand() {
double *localArray = new double[size + 1];
for (int i = 0; i < size; i++) {
localArray[i] = arr[i];
}
localArray[size] = size;
delete [] arr;
setSize(size + 1);
arr = localArray;
// myArray = new int[size];
//
// //Is this a deep-copy or a shallow-copy?
// //Can you replace one with the other?
// //What are the advantages and disadvantages?
// for(int i=0; i < size; i++) {
// myArray[i] = localArray[i];
// }
// delete [] localArray;
}
bool myArray::equal(const myArray& rhs) const {
bool result(true);
if (getSize() != rhs.getSize()) {
result = false;
} else {
for (int i = 0; i < getSize(); i++) {
if (getData(i) != rhs.getData(i)) {
result = false;
}
}
}
return result;
}
void myArray::init()
{
cout << "Enter the " << size << " elements to populate the array " << endl;
for(int i = 0;i<getSize();i++)
{
int value;
cin >> value;
setData(i,value);
}
}
Sorry I somehow I thought you wanted help with a runtime error but you want help with the compile errors.
The compile error in this part of the code
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
is specifically about the orig.getSize() part. orig is of type double* (pointer to double) and pointers do not have member functions only classes do which is why the compiler says: "which is non-class type double"
Actually there is no way in c++ to know from a pointer to how many elements it points but luckily your function already has a parameter size which i guess is meant to pass in the size of the orig array. So that line should be setSize(size);
Now two lines lower you get a similar error on setData(i,orig.getData(i)); orig is still a double* so it still doesn't have member functions. The correct way is setData(i, orig[i]);
EDIT:
BTW, i quick look through the rest of your code shows me that your setSize method doesn't allocate an array of appropriate size so you should fix that to.
Here is some random sort program I wrote in C++. It works pretty fine for 10 elements or so. But for 15 elements it works so slow I can't even wait enough to get the result. Is there some way to optimize random sort algorithm?
Here's my code:
// randomsort.h
#ifndef RANDOMSORT_H
#define RANDOMSORT_H
#include <stdlib.h>
#include <time.h>
class RandomSort
{
private:
template <class T>
static bool isOrdered(T*, int);
public:
template <class T>
static int sort(T*, int);
};
template <class T>
bool RandomSort::isOrdered(T* arr, int size)
{
for(int i = 1; i < size; i++)
{
if(arr[i-1] > arr[i])
{
return false;
}
}
return true;
}
template <class T>
int RandomSort::sort(T* arr, int size)
{
int stepAmount = 0;
srand(time(NULL));
while(!isOrdered(arr, size))
{
int i = rand() % size;
int j = rand() % size;
std::swap(arr[i], arr[j]);
stepAmount++;
}
return stepAmount;
}
#endif // RANDOMSORT_H
And main.cpp file
// main.cpp
#include <iostream>
#include "randomsort.h"
int main()
{
int size;
std::cout << "Enter amount of elements to sort: ";
std::cin >> size;
std::cout << std::endl;
int arr[size];
for(int i = 0; i < size; i++)
{
arr[i] = (rand() % (size * 10));
}
std::cout << "Input array: " << std::endl;
for(int i = 0; i < size; i++)
std::cout << arr[i] << ' ';
std::cout << std::endl << std::endl;
int stepAmount = RandomSort::sort(arr, size);
std::cout << "Output array: " << std::endl;
for(int i = 0; i < size; i++)
std::cout << arr[i] << ' ';
std::cout << std::endl << std::endl;
std::cout << "Number of steps: " << stepAmount;
return 0;
}
Any suggestions?
Your code is completely random. So it can swap when it should not. An easy fix would be to swap only if you need it.
int i = rand() % size;
int j = rand() % size;
// to know which should be first
if (i > j)
std::swap(i, j);
if (arr[i] > arr[j])
std::swap(arr[i], arr[j]);
Your array probably will not be sorted immediately, so you could also test if it is sorted only every five steps (for example) instead of every step.
But i think the most important is, you should not expect good performances from such an algorithm.
I am trying to take in an input for the dimensions of a 2D matrix. And then use user input to fill in this matrix. The way I tried doing this is via vectors (vectors of vectors). But I have encountered some errors whenever I try to read in data and append it to the matrix.
//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
for(int j = 0; j<CC; j++)
{
cout<<"Enter the number for Matrix 1";
cin>>matrix[i][j];
}
}
Whenever I try to do this, it gives me a subscript out of range error. Any advice?
You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:
// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));
This creates a vector of RR size CC vectors, filled with 0.
As it is, both dimensions of your vector are 0.
Instead, initialize the vector as this:
vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
matrix[i].resize(CC);
This will give you a matrix of dimensions RR * CC with all elements set to 0.
I'm not familiar with c++, but a quick look at the documentation suggests that this should work:
//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
vector<int> myvector;
for(int j = 0; j<CC; j++)
{
int tempVal = 0;
cout<<"Enter the number for Matrix 1";
cin>>tempVal;
myvector.push_back(tempVal);
}
matrix.push_back(myvector);
}
Assume we have the following class:
#include <vector>
class Matrix {
private:
std::vector<std::vector<int>> data;
};
First of all I would like suggest you to implement a default constructor:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
private:
std::vector<std::vector<int>> data;
};
At this time we can create Matrix instance as follows:
Matrix one;
The next strategic step is to implement a Reset method, which takes two integer parameters that specify the new number of rows and columns of the matrix, respectively:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
if (rows == 0 || cols == 0) {
data.assign(0, std::vector<int>(0));
} else {
data.assign(rows, std::vector<int>(cols));
}
}
private:
std::vector<std::vector<int>> data;
};
At this time the Reset method changes the dimensions of the 2D-matrix to the given ones and resets all its elements. Let me show you a bit later why we may need this.
Well, we can create and initialize our matrix:
Matrix two(3, 5);
Lets add info methods for our matrix:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
At this time we can get some trivial matrix debug info:
#include <iostream>
void MatrixInfo(const Matrix& m) {
std::cout << "{ \"rows\": " << m.GetNumRows()
<< ", \"cols\": " << m.GetNumColumns() << " }" << std::endl;
}
int main() {
Matrix three(3, 4);
MatrixInfo(three);
}
The second class method we need at this time is At. A sort of getter for our private data:
#include <vector>
class Matrix {
public:
Matrix(): data({}) {}
Matrix(const int &rows, const int &cols) {
Reset(rows, cols);
}
void Reset(const int &rows, const int &cols) {
data.resize(rows);
for (int i = 0; i < rows; ++i) {
data.at(i).resize(cols);
}
}
int At(const int &row, const int &col) const {
return data.at(row).at(col);
}
int& At(const int &row, const int &col) {
return data.at(row).at(col);
}
int GetNumRows() const {
return data.size();
}
int GetNumColumns() const {
if (GetNumRows() > 0) {
return data[0].size();
}
return 0;
}
private:
std::vector<std::vector<int>> data;
};
The constant At method takes the row number and column number and returns the value in the corresponding matrix cell:
#include <iostream>
int main() {
Matrix three(3, 4);
std::cout << three.At(1, 2); // 0 at this time
}
The second, non-constant At method with the same parameters returns a reference to the value in the corresponding matrix cell:
#include <iostream>
int main() {
Matrix three(3, 4);
three.At(1, 2) = 8;
std::cout << three.At(1, 2); // 8
}
Finally lets implement >> operator:
#include <iostream>
std::istream& operator>>(std::istream& stream, Matrix &matrix) {
int row = 0, col = 0;
stream >> row >> col;
matrix.Reset(row, col);
for (int r = 0; r < row; ++r) {
for (int c = 0; c < col; ++c) {
stream >> matrix.At(r, c);
}
}
return stream;
}
And test it:
#include <iostream>
int main() {
Matrix four; // An empty matrix
MatrixInfo(four);
// Example output:
//
// { "rows": 0, "cols": 0 }
std::cin >> four;
// Example input
//
// 2 3
// 4 -1 10
// 8 7 13
MatrixInfo(four);
// Example output:
//
// { "rows": 2, "cols": 3 }
}
Feel free to add out of range check. I hope this example helps you :)
try this. m = row, n = col
vector<vector<int>> matrix(m, vector<int>(n));
for(i = 0;i < m; i++)
{
for(j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
cout << endl;
}
cout << "::matrix::" << endl;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
Vector needs to be initialized before using it as cin>>v[i][j]. Even if it was 1D vector, it still needs an initialization, see this link
After initialization there will be no errors, see this link
What you have initialized is a vector of vectors, so you definitely have to include a vector to be inserted("Pushed" in the terminology of vectors) in the original vector you have named matrix in your example.
One more thing, you cannot directly insert values in the vector using the operator "cin". Use a variable which takes input and then insert the same in the vector.
Please try this out :
int num;
for(int i=0; i<RR; i++){
vector<int>inter_mat; //Intermediate matrix to help insert(push) contents of whole row at a time
for(int j=0; j<CC; j++){
cin>>num; //Extra variable in helping push our number to vector
vin.push_back(num); //Inserting numbers in a row, one by one
}
v.push_back(vin); //Inserting the whole row at once to original 2D matrix
}
I did this class for that purpose. it produces a variable size matrix ( expandable) when more items are added
'''
#pragma once
#include<vector>
#include<iostream>
#include<iomanip>
using namespace std;
template <class T>class Matrix
{
public:
Matrix() = default;
bool AddItem(unsigned r, unsigned c, T value)
{
if (r >= Rows_count)
{
Rows.resize(r + 1);
Rows_count = r + 1;
}
else
{
Rows.resize(Rows_count);
}
if (c >= Columns_Count )
{
for (std::vector<T>& row : Rows)
{
row.resize(c + 1);
}
Columns_Count = c + 1;
}
else
{
for (std::vector<T>& row : Rows)
{
row.resize(Columns_Count);
}
}
if (r < Rows.size())
if (c < static_cast<std::vector<T>>(Rows.at(r)).size())
{
(Rows.at(r)).at(c) = value;
}
else
{
cout << Rows.at(r).size() << " greater than " << c << endl;
}
else
cout << "ERROR" << endl;
return true;
}
void Show()
{
std::cout << "*****************"<<std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " <<setw(5)<< c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
void Show(size_t n)
{
std::cout << "*****************" << std::endl;
for (std::vector<T> r : Rows)
{
for (auto& c : r)
std::cout << " " << setw(n) << c;
std::cout << std::endl;
}
std::cout << "*****************" << std::endl;
}
// ~Matrix();
public:
std::vector<std::vector<T>> Rows;
unsigned Rows_count;
unsigned Columns_Count;
};
'''