Vector subscript out of range Visual Studio C++ - c++

I'm working with matrices in C++. The task is to find odd numbers in a matrix. I created a function, but when executed with Debug > Start Without Debugging... I get the error:
Debug assertion failed. Expression: vector subscript out of range.
This is my code:
File MatrixVec.h:
#include "MatrixVec.h"
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
MatrixVec::MatrixVec(int rows, int cols, int range)
{
row.assign(cols, 0);
mat.assign(rows, row);
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[i].size(); j++){
mat[i][j] = rand() % range;
}
}
}
void MatrixVec::process()
{
int *oddNum = new int(mat[0].size());
for (int i = 0; i < mat[0].size(); i++) {
oddNum[i] = 0;
}
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[0].size(); j++) {
oddNum[j] += mat[i][j] % 2;
}
}
for (int i = 0; i < mat[0].size(); i++) {
cout << i + 1 << ". kolona " << oddNum[i]<< " neparnih elemenata." << endl;
}
//Edit
delete[] oddNum; //forgot this line
}
File MatrixVec.h:
#include "Matrix.h"
#include <vector>
class MatrixVec : public Matrix {
public:
MatrixVec(int rows, int cols, int range);
void print();
void process();
private:
std::vector<int> row;
std::vector<std::vector<int> > mat;
};
File Matrix.h:
class Matrix {
public:
virtual void print() = 0;
virtual void process() = 0;
};
File main.cpp
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include "Matrix1D.h"
#include "Matrix2D.h"
#include "MatrixVec.h"
using namespace std;
#define NUMBER_RANGE 10
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout << "Niste uneli potrebne argumente za pokretanje programa!" << endl;
cout << "Argumenti komandne linije treba da budu:" << endl;
cout << "1. N dimenzija matrice" << endl;
cout << "2. M dimenzija matrice" << endl;
exit(-1);
}
// inicijalizacija generatora nasumičnih brojeva
srand(unsigned int(time(NULL)));
int rowNum = atoi(argv[1]);
int colNum = atoi(argv[2]);
// a)
cout << endl << endl << "a) Matrix 1D representation" << endl;
Matrix1D mat1(rowNum, colNum, 10);
mat1.print();
mat1.process();
//b)
cout << endl << endl << "b) Matrix 2D representation" << endl;
Matrix2D mat2(rowNum, colNum, 10);
mat2.print();
mat2.process();
//c)
cout << endl << endl << "c) Matrix vector of vector representation" << endl;
MatrixVec mat3(rowNum, colNum, 10);
mat3.print();
mat3.process();
return 0;
}

This line int *oddNum = new int(mat[0].size()); actually creating one int with value of mat[0].size(). You want something like this to create an array of size mat[0].size().
int *oddNum = new int[mat[0].size()];
Note: This still not answer the exact error. Seems like your mat vector is empty.

Related

How do I use the dot operator on a 2D Vector of my class while accessing a function of that class?

I have trouble explaining what I'm trying to do--sorry if i botched the title: so, I made a 2D Vector. The 2D Vector is an object of my class which is named Matrix. I tried doing matrix.fill2dVector(numRows,numCols), and I would get these errors:
class "std::vector<std::vector<Matrix, std::allocator<Matrix>>, std::allocator<std::vector<Matrix, std::allocator<Matrix>>>>" has no member "fill2dVector"
'fill2dVector': is not a member of 'std::vector<std::vector<Matrix,std::allocator<_Ty>>,std::allocator<std::vector<_Ty,std::allocator<_Ty>>>>'
I can see that it's trying to find fill2dVector inside the STL vector container; but, I don't want it to do that. Also, I'm stuck using the functions in the prototypes since this is an assignment for my class, but I am allowed to modify them.
#include <iostream>
#include <vector>
class Matrix
{
public:
Matrix();
double& operator()(const int rn, const int cn);
void operator()();
void fill2dVector(int &numRows, int &numCols);
void display2dVector(int &numRows, int &numCols) const;
private:
int numRows = 10, numCols = 10;
std::vector<std::vector <double>> data;
};
Matrix::Matrix()
{
data[10][10] = {};
}
double& Matrix::operator()(const int rn, const int cn)
{
return data[rn][cn];
}
void Matrix::operator()()
{
for (int r = 0; r < numRows; ++r)
{
for (int c = 0; c < numCols; ++c)
{
data[r][c] = 0;
}
}
}
void Matrix::display2dVector(int &numRows, int &numCols) const
{
for (int r = 0; r < numRows; ++r)
{
for (int c = 0; c < numCols; ++c)
{
std::cout << " " << data[r][c] << " ";
}
std::cout << std::endl;
}
}
void Matrix::fill2dVector(int &numRows, int &numCols)
{
for (int r = 0; r < numRows; ++r)
{
std::cout << "Enter " << numCols << " values for row #" << r << std::endl;
for (int c = 0; c < numCols; ++c)
{
std::cin >> data[r][c];
}
std::cout << std::endl;
}
}
int main()
{
std::cout << "Enter the size of the matrix:" << std::endl;
std::cout << " How many rows? ";
int numRows;
std::cin >> numRows;
std::cout << "How many columns? ";
int numCols;
std::cin >> numCols;
std::cout << std::endl;
std::cout << "*** numRows = " << numRows << ", " << "numCols = " << numCols << std::endl;
std::vector< std::vector <Matrix> > matrix;
std::cout << "Contents of the " << numRows << " x " << numCols << " vector:" << std::endl;
matrix.fill2dVector(numRows,numCols);
}
Instead of :
std::vector< std::vector <Matrix> > matrix;
Write :
Matrix matrix;
Also your matrix implementation is broken because you access vector elements without allocation and while filling doesn't check for vector size so you can get into an access out of bounds and why are you passing those ints by reference ?
I am not 100% sure if I understand your question so I think
I provide a code sample on accessing a 3d vector object I wrote
a while ago and my guess is, this will really help you solve your
Question. Just remove one layer for accessing a 2d vector.
With that Example code you should be able to solve your question.
There is also a <random> example referring to another question of yours.
#include <iostream> // cout
#include <vector> // vector
#include <random> //rand, srand
#include <algorithm> //shuffle
#include <string> //using strings
#include <limits> //cin
using my_engine = std::random_device; //most random
class deck
{
std::string comment;
public:
void output(std::string); //txt output
void display_card_deck();//display all cards
void mix_cards(); //delete and remix deck new game
size_t getCards(size_t playnum, size_t color, size_t number);
private:
size_t _inp_check(); //input player number + check
std::vector < std::vector < std::vector < size_t > > > _card_deck; //assign 3d vector
void _shuffle_cards(size_t players); //mix and shuffle cards randomly
};
void deck::output(std::string comment)
{
std::cout << comment << " cards are used for " << _card_deck.size() << std::endl;
}
int main()
{
deck play;
//round 1
play.mix_cards(); //mix cards randomly and input player number 2-8
play.output ("Welcome Player ... and Player ... "); //text, number of players
std::cout << play.getCards(0,2,2) << "test output" << std::endl; //pick one card
//round 2
play.mix_cards();
std::cout << play.getCards(0,2,2) << std::endl; //pick one card
play.output ("Welcome Player ... and Player ... "); //text, number of players
play.display_card_deck();
return 0;
}
//members of deck class
size_t deck :: _inp_check()
{
size_t input;
while (!(std::cin >> input) || input < 2 || input > 8)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Try again and enter a valid player number from 2 to 8: "<< "\n";
}
return input;
}
void deck :: mix_cards()
{
if (_card_deck.empty())
{
std::cout << "How many Players are playing today? (2-8):" << std::endl;
size_t players = _inp_check();
_shuffle_cards(players);
}
else
{
std::cout << "How many Players are playing today? (2-8):" << std::endl;
_card_deck.clear();
size_t players = _inp_check();
_shuffle_cards(players);
}
}
void deck :: _shuffle_cards(size_t players)
{
my_engine engn; //random_device
for(size_t playnum = 0; playnum < players; ++playnum)
{
std::vector < std::vector < size_t > > d1;
_card_deck.push_back( d1 );
for(size_t color = 0; color < 4; color++)
{
std::vector < size_t > d2;
_card_deck[playnum].push_back( d2 );
for(size_t k = 1; k < 11; k++)
{
_card_deck[playnum][color].push_back( k ); //1 2 3 4 5 6 7 8 9 10
}
shuffle(_card_deck[playnum][color].begin(), _card_deck[playnum][color].end(), engn);
}
}
}
void deck :: display_card_deck()
{
for (size_t i = 0; i < _card_deck.size(); i++)
{
for (size_t j = 0; j < _card_deck[i].size(); j++)
{
for (size_t k = 0; k < _card_deck[i][j].size(); k++)
{
std::cout << "_card_deck[" << i << "][" << j << "][" << k << "] = " << _card_deck[i][j][k] << std::endl;
}
}
}
}
size_t deck::getCards(size_t playnum, size_t color, size_t number)
{
return _card_deck[playnum][color][number];
}

tic tac toe board which size is based on user input

I am working on a tic tac toe game and need to create a function which creates the board based on user input. Can be 3x3 or bigger I have this so far but when I run it prints memory location.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Array which creates boeard based on user input
int *drawboard(int width, int height)
{
int* board_data = new int[width * height];
int** board = new int* [width];
for (int i = 0; i < width; ++i)
{
board[i] = board_data + height * i;
}
return board_data;
}
void main()
{
int width = 0;
int height = 0;
cout << " Welcome to Tic Tac Toe v1! " << endl;
cout << " Choose your board size, enter width: " << endl;
cin >> width;
cout << " Choose your height: " << endl;
cin >> height;
cout << drawboard << endl;
int *board = drawboard(width, height);
delete[] board;
system("pause");
}
I think this post will help you out a lot. It seems you're just trying to declare a dynamic 2D array of integers, then use the virtual 2D array as a tic tac toe board, right?
Not quite sure what you mean by drawboard(), but here's a simple way to print a grid:
void printGrid(int y, int x) {
for (int j = 0; j < y; j++) {
for (int i = 0; i < x; i++) cout << " ---";
cout << endl;
for (int i = 0; i < x; i++) cout << "| ";
cout << "|" << endl;
}
for (int i = 0; i < x; i++) cout << " ---";
cout << endl;
}
This is my code when I run it my output is
AAA
BBB
CCC
if I input 3x3 board
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
using namespace std;
// Array which creates boeard based on user input
char **createboard(int rows, int cols)
{
char** boardArray = new char*[rows];
for (int i = 0; i < rows; ++i) {
boardArray[i] = new char[cols];
}
// Fill the array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
boardArray[i][j] = char(i + 65);
}
}
// Output the array
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << boardArray[i][j];
}
cout << endl;
}
// Deallocate memory by deleting
for (int i = 0; i < rows; ++i) {
delete[] boardArray[i];
}
delete[] boardArray;
return boardArray;
}
int main()
{
int rows = 0;
int cols = 0;
char **boardArray = createboard(rows, cols);
cout << " Welcome to Tic Tac Toe v1! " << endl;
cout << " Choose your board width: " << endl;
cin >> rows;
cout << " Choose your board height " << endl;
cin >> cols;
cout << endl;
createboard(rows, cols);
system("pause");
}

How to: return multidimensional vector (Matrix) from function - using header

I'd like to read a matrix from cin, using a function, then return matrix back to main.
Here's my code:
main.cpp
#include <iostream>
#include <windows.h>
#include <vector>
#include "mymath.h"
using namespace std;
int main(){
vector<vector<double>> matrix_read();
Sleep(60000);
return 0;
}
mymath.h
#pragma once
#ifndef MYMATH_H
#define MYMATH_H
vector<vector<double>> matrix_read();
#endif
mymath.cpp
#include "mymath.h"
#include <vector>
#include <iostream>
using namespace std;
vector<vector<double>> matrix_read() {
cout << "How big is the quadratic matrix A?\n";
int n;
//row&column size A
cin >> n;
vector<vector<double>> A(n, vector<double>(n));
//fill matrix A
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
//control matrix A:
cout << "Please be sure this is the correct Matrix A: \n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
return A;
}
for reference:
Return multidimensional vector from function for use in main, how to use correctly?
Error list
What is my error?
The error list implies there's a major mistake. Thank you for your help. Please be gentle, newbie here.
You need to prefix vector with std::vector in the header, if you did not have using namespace std; before the include directive. Anyway, it's good practice to have std:: in the header.
In main, it should be
int main(){
vector<vector<double>> matrix = matrix_read();
Sleep(60000);
return 0;
}
i.e. you set the object matrix to the return value of the function. Otherwise, you would define another prototype for matrix_read in the main function.
Maximilian Matthé was right. Here's the working code:
mymath.h
#pragma once
#include <vector>
#include <iostream>
std::vector<std::vector<double>> matrix_read();
mymath.cpp
#include "mymath.h"
std::vector<std::vector<double>> matrix_read() {
std::cout << "How big is the quadratic matrix A?\n";
int n;
//row&column size A
std::cin >> n;
std::vector<std::vector<double>> A(n, std::vector<double>(n));
//fill matrix A
int j = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << "Please enter the value for A" << "[" << i + 1 << "]" << "[" << j + 1 << "]\n";
std::cin >> A[i][j];
}
}
//control matrix A:
std::cout << "Please be sure this is the correct Matrix A: \n\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}
return A;
}
main.cpp
#include <windows.h>
#include "mymath.h"
int main() {
std::vector<std::vector<double>> A = matrix_read();
Sleep(60000);
return 0;
}

C++ Parallel Arrays

In this Parallel Array I can not see or figure out why I am printing the memory address instead of the values Entered. I ask the C++ gods to enlighten me and Point me to some good tutorials about this issue so that I can learn from. Code is below.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ios>
using namespace std;
// Assign a constant
const int rowSize = 6;
const int columnSize = 4;
void displayWelcome()
{
cout << "\tCorporation X\n";
cout << "Quartily Reports for the six Entities\n";
cout << "Showing you the Highest Average out of the six\n";
cout << endl;
}
// Assign Words in a row of 6
string* entitiesArray(string(entities)[rowSize])
{
string entitiesName[rowSize] = {"East ","West ","Central ","Midwest"
,"South ","South East "};
//string entitiesName;
for(int i=0; i < rowSize; i++)
{
cout << entitiesName[i] << endl;
}
return entitiesName;
}
// Assign numbers to a 6x4
double* entriesArray(double(corpArray)[rowSize][columnSize])
{
// Assign Random Numbers to the Array
srand(time(0));
double rowSum = 0.0, average = 0.0;
for (int r = 0; r < rowSize; ++r)
{
rowSum = 0;
for (int c = 0; c < columnSize; ++c)
{
corpArray[r][c] = rand() % 101;
cout << setw(5) << left << corpArray[r][c] << " ";
rowSum += corpArray[r][c];
average = rowSum / 4;
}
cout << average;
cout << endl;
}
return 0;
}
// Parallel Array This is where is prints the Memory Address
void pArray(string &theEntitiesArray,double &theEntriesArray)
{
string entity = &theEntitiesArray;
double entry = &theEntriesArray;
for(int row_index = 0; row_index < 6; row_index++)
{
cout << setw(10) << entity <<endl;
for (int col_index = 0; col_index < 4; col_index++)
{
cout << setw(10) << entry << endl;
}
}
}
int main(int argc, const char * argv[])
{
// Declare an Array & Variables
double corpArray[rowSize][columnSize];
string entities[rowSize];
double* theEntriesArray;
string* theEntitiesArray;
char parallelArray;
displayWelcome();
theEntitiesArray = entitiesArray(entities);
theEntriesArray = entriesArray(corpArray);
pArray(*theEntitiesArray, *theEntriesArray);
cout << endl;
return 0;
}
#JSF beat me to it in a comment, but in the line double entry = &theEntriesArray;, you're assigning the address of theEntriesArray to the variable entry, rather than the numerical value it refers to. Change it to:
double entry = theEntriesArray;
You have Some Problems in Functions which initzlize the array now its fine try to read about pointer
1- http://www.cplusplus.com/doc/tutorial/pointers/
2- http://www.tutorialspoint.com/cplusplus/cpp_pointer_to_pointer.htm
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <ios>
using namespace std;
// Assign a constant
const int rowSize = 6;
const int columnSize = 4;
void displayWelcome()
{
cout << "\tCorporation X\n";
cout << "Quartily Reports for the six Entities\n";
cout << "Showing you the Highest Average out of the six\n";
cout << endl;
}
// Assign Words in a row of 6
string* entitiesArray(string(entities)[rowSize])
{
string* entitiesName = new string[rowSize];
string temp[]= { "East ", "West ", "Central ", "Midwest"
, "South ", "South East " };
for (int i = 0; i < rowSize; i++)
{
entitiesName[i] = temp[i];
}
//string entitiesName;
for (int i = 0; i < rowSize; i++)
{
cout << entitiesName[i] << endl;
}
return entitiesName;
}
// Assign numbers to a 6x4
double** entriesArray(double(corpArray)[rowSize][columnSize])
{
double** tempcorpArray = new double*[rowSize];// [columnSize];
for (int i = 0; i < rowSize; ++i)
{
tempcorpArray[i] = new double[columnSize];
}
// Assign Random Numbers to the Array
srand(time(0));
double rowSum = 0.0, average = 0.0;
for (int r = 0; r < rowSize; ++r)
{
rowSum = 0;
for (int c = 0; c < columnSize; ++c)
{
tempcorpArray[r][c] = rand() % 101;
cout << setw(5) << left << tempcorpArray[r][c] << " ";
rowSum += tempcorpArray[r][c];
average = rowSum / 4;
}
cout << average;
cout << endl;
}
return tempcorpArray;
}
// Parallel Array This is where is prints the Memory Address
void pArray(string* theEntitiesArray, double** theEntriesArray )
{
string* entity = theEntitiesArray;
double** entry = theEntriesArray;
for (int row_index = 0; row_index < 6; row_index++)
{
cout << setw(10) << (entity[row_index]) << endl;
for (int col_index = 0; col_index < 4; col_index++)
{
cout << setw(10) << (entry[row_index][col_index]) << endl;
}
}
}
int main(int argc, const char * argv[])
{
// Declare an Array & Variables
double corpArray[rowSize][columnSize];
string entities[rowSize];
char parallelArray;
displayWelcome();
string* theEntitiesArray = entitiesArray(entities);
double** theEntriesArray = entriesArray(corpArray);
pArray(theEntitiesArray, theEntriesArray);
cout << endl;
return 0;
}
if there is any problem feel free to ask :D

Matrix Overload C++

In the header file I am suppose to add the declaration of functions which I need to overload operators. Then implement the functions I added into the header file.
Can any one help me with what I am suppose to do? Please explain so I can wrap my head around overloading if possible.
I have listed the code below. As for main I am not suppose to edit it.
Header File
Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
class Matrix
{
public:
Matrix (int sizeX, int sizeY);
~Matrix();
int GetSizeX() const { return dx; }
int GetSizeY() const { return dy; }
long &Element(int x, int y); // return reference to an element
void Print () const;
private:
long **p; // pointer to a pointer to a long integer
int dx, dy;
};
#endif /* MATRIX_H */
Matrix.cpp File
#include <iostream>
#include <cassert>
#include "Matrix.h"
using namespace std;
Matrix::Matrix (int sizeX, int sizeY) : dx(sizeX), dy(sizeY)
{
assert(sizeX > 0 && sizeY > 0);
p = new long*[dx];
// create array of pointers to long integers
assert(p != 0);
for (int i = 0; i < dx; i++)
{ // for each pointer, create array of long integers
p[i] = new long[dy];
assert(p[i] != 0);
for (int j = 0; j < dy; j++)
p[i][j] = 0;
}
}
Matrix::~Matrix()
{
for (int i = 0; i < dx; i++)
delete [] p[i]; // delete arrays of long integers
delete [] p; // delete array of pointers to long
}
long &Matrix::Element(int x, int y)
{
assert(x >= 0 && x < dx && y >= 0 && y < dy);
return p[x][y];
}
void Matrix::Print () const
{
cout << endl;
for (int x = 0; x < dx; x++)
{
for (int y = 0; y < dy; y++)
cout << p[x][y] << "\t";
cout << endl;
}
}
main.cpp
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <ctime>
#include "Matrix.h"
using namespace std;
int main(int argc, char** argv) {
int size1, size2, size3;
const int RANGE = 5; //using to generate random number in the range[1,6]
cout << "Please input three positive integers: (size)";
cin >> size1 >> size2 >> size3;
assert(size1 > 0 && size2 > 0 && size3 > 0);
Matrix myMatrix1(size1, size2), myMatrix2(size2,size3);
Matrix yourMatrix1(size1, size2), yourMatrix2(size2, size3);
Matrix theirMatrix1(size1, size2), theirMatrix2(size1, size3);
srand(time(0));
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
myMatrix1(i,j) = rand() % RANGE + 1;
yourMatrix1 = 2 * myMatrix1;
theirMatrix1 = myMatrix1 + yourMatrix1;
cout << "myMatrix1: " << endl;
cout << myMatrix1 << endl << endl;
cout << "yourMatrix1 = 2 * myMatrix " << endl;
cout << yourMatrix1 << endl << endl;
cout << "myMatrix1 + yourMatrix1: " << endl;
cout << theirMatrix1 << endl << endl;
for (int i = 0; i < size2; i++)
for (int j = 0; j < size3; j++)
myMatrix2(i,j) = rand() % RANGE + 1;
yourMatrix2 = myMatrix2 * 3;
theirMatrix2 = myMatrix1 * yourMatrix2;
cout << "myMatrix1: " << endl;
cout << myMatrix1 << endl << endl;
cout << "myMatrix2: " << endl;
cout << myMatrix2 << endl << endl;
cout << "yourMatrix2 = myMatrix2 * 3 " << endl;
cout << yourMatrix2 << endl << endl;
cout << "myMatrix1 * yourMatrix2: " << endl;
cout << theirMatrix2 << endl << endl;
return 0;
}
You need to look into the main and see what all operators are used with the Matrix objects. You have to overload those operators into the Matrix class given to you i.e. write member functions into this class.
Refer following link for details on operator overloading with examples:
http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading