input 2D vector in main() c++ - c++

I am novice in vectors, I am tryind to input this 2D vector in main() function, but unable to do so.
int main()
{
int t, x, n;
cin>>n;
vector< vector <int> > jail(n);
for(int i=0; i<n; i++){
jail[i].reserve(n);
for(int j=0; j<n; j++){
cin>>jail[i][j];
}
}
cout<< jailBreak(jail,n-1,0,0)<<endl;
}
Runtime error is that I need to input an garbage input in the beginning of the program.
This ambiguous input has been bothering me for a long time now, thanx in advance for any advice on this.!

this line:
jail[i].reserve(n);
just tells vector to pre-allocate memory (it's just a hint to optimize further reallocs on push_back operations but does not guarantee allocation). You have to use resize instead which really allocates memory.

In your code:
for(int i=0; i<n; i++){
jail[i].reserve(n);
for(int j=0; j<n; j++){
cin>>jail[i][j];
}
}
jail[i].reserve(n);
should be jail[i].resize(n)
cin>>jail[i][j]
Never seen that work before. cin in to a temporary and then push.
int temp;
std::cin >> temp;
jail[i].emplace_back(temp);

Related

Assign values to a 2D vector from a file on c++

Im trying to assign values to a 2d vector, this is the way that i defined the vector, and also its important to say that rows and columns, are ints previously defined
vector < vector <int>> vec(rows , vector <int> (columns,0));
i want to assign to this vector, each char of a pbm file, this file only have '1' and '0', so this is the way im reading it
char i;
FILE* fp;
fp = fopen("file.pbm", "r");
on this way im assigning values to the vector
for (int h=0; h<rows; h++){
for (int j=0; j<columns; j++){
while((i=fgetc(fp))!=EOF){
vec[h][j] = i;
}
}
}
but when i try to print all the vector content, this one, only have '0'
for (int h=0; h<rows; h++){
for (int j=0; j<columns; j++)
cout << vec[h][j];
cout <<endl;
}
fclose(fp);
If anyone could tell me where im failing when i make this assignment, thanks!
vec[h][j] = i;
for (int h=0; h<rows; h++){
for (int j=0; j<columns; j++){
while((i=fgetc(fp))!=EOF){
vec[h][j] = i;
}
}
}
The while loop runs through the entire file without ever incrementing h and j so you are reading the whole file into the first element. And you are doing this (rows*columns) times.
You'll need to redesign your code to read the code in correctly.

What is the missing step here to insert random numbers into the array (c++)?

I am trying to insert random numbers [1;100] into this array of 5 elements but so far I've been using only cin>> for inserting, when the user had to put something in. In this case I would like the random function to insert numbers, no user involved.
I show the code below because I am a beginner and the included pieces of codes are mostly what I can use and understand but on the other hand the whole code is useless because I don't know what is to connect with what. Where is rand()%100+1 to put?
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
int a[5];
int r=rand()%100+1;
for(int i=0; i<5; i++)
{
cout<<a[i]<<endl;
}
for(int i=0; i<5; i++)
{
cout<<a[i]<<endl;
}
return 0;
}
In your program you have 2 loops that both print out result. I suppose previously you had one loop that used cin to insert values, like this:
for(int i=0; i<5; i++)
{
cin<<a[i]<<endl;
}
So you want to change from inserting with ci to inserting random number:
for(int i=0; i<5; i++)
{
a[i] = rand()%100+1
}
In your code you are not initializing the values of the array elements using the rand() function.
Your rand function should go inside the first 'for' loop.Something like the following will do the trick.
for (int i = 0; i < 5; i++) {
a[i] = rand()%100+1;
}

Create and delete triple pointer of dimensions [3N][N][3] with N=2, mysterious seg fault

I have a problem programming in C++, I want to create and delete a triple pointer with dimension [3N][N][3], and I keep getting seg-fault without knowing in which line the error is...(N is an integer, N=2 to start)
#include <stdio.h>
#include <cmath>
#include <stdlib.h>
using namespace std;
int N=2;
int main(void){
double ***individuo;
individuo=new double**[3*N];
for(int k=0; k<3*N; ++k){
individuo[k]=new double*[3];
for(int i=0; i<N; ++i){
individuo[k][i]=new double[N];
}
}
for(int k=0; k<3*N; ++k){
for(int i=0; i<N; ++i){
delete []individuo[k][i];
}
delete []individuo[k];
}
delete []individuo;
return 0;
}
Looks like your first set of for loops is setting up the array with dimensions [3N][3][N], and then your second set is calling them as if it was dimensioned as [3N][N][]. This means that you aren't correctly accounting for all your allocated memory in the delete process.
You can use a debugger to find out where your code is giving the segfault. Or if you don't have one it's often useful to put in some unique print statements at various stages to try and find where it is giving the fault. Although make sure that the print statements are flushed from the buffer, most easily done using std::endl.
This
for(int k=0; k<3*N; ++k){
individuo[k]=new double*[3];
for(int i=0; i<N; ++i){
individuo[k][i]=new double[N];
}
}
should instead be this
for(int k=0; k<3*N; ++k){
individuo[k]=new double*[N];
for(int i=0; i<N; ++i){
individuo[k][i]=new double[3];
}
}

Why is cycle stopping?

I have a program with bool function issquare, which code don't need for you for my question. I have iterative variable T, which is response for how many times I will put squarsized's time string. But after first input of strings programs stop, at T=1, and don't go to next iteration. Why?
int main(){
int T;
std::string line;
std::cin>>T;
int squaresize;
int** arr=new int*[30];
for(int d=0; d<30; d++){
arr[d]=new int[30];
}
for(int i=0; i<T; i++){
for (int d=0; d<30; d++){
for(int d1=0; d<30; d++){
arr[d][d1]=0;
}
}
std::cin>>squaresize;
for(int j=0; i<squaresize; i++){
std::cin>>line;
for(int a=0; a<squaresize; a++){
if (line[a]=='#'){
arr[j][a]=1;
}
}
}
if (issquare(arr, squaresize)==true){
std::cout<<"Case #"<<i+1<<": YES";
}
else{
std::cout<<"Case #"<<i+1<<": NO";
}
std::cout<<T;
}
return 0;
}
Instead of
std::cin>>line;
Try
getline(std::cin, line);
operator>> doesn't read an entire line, only until the first whitespace.
Instead of j you are comparing and incrementing i, which is also used by the outer loop:
for(int j=0; i<squaresize; i++){
std::cin>>line;
for(int a=0; a<squaresize; a++){
if (line[a]=='#'){
arr[j][a]=1;
}
}
}
In the future (and with possibly more complex programs), learning how to use of a debugger can really help you to locate such bugs. Your problem was that the outmost loop executed less than T times:
for(int i=0; i<T; i++){
Since the value of T is constant, something must be modifying i inside the loop. An easy way to debug this would be using a debugger to find out where the variable is changed. In Visual Studio this can be done by breaking and adding a data breakpoint from Debug -> New Breakpoint -> New Data Breakpoint -> Address: &i

Redefining operators c++

I tried to redefine + operator which was to sum 2 matrices and return the summation matrice in c++. But somehow it displays 0 all the time. What I'm missing? Here is my code.
Also I've written this code.
#include <iostream>
using namespace std;
class matrix{
public:
int a[100][100], n;
matrix(int b[100][100], int n){
for(int i=0; i<n; i++){
for(int l=0; l<n; l++){
a[i][l]=b[i][l];
}
}
n=n;
}
matrix(){}
void matrix_input(int n){
for(int i=0; i<n; i++){
for(int l=0; l<n; l++){
cin >> a[i][l];
}
}
}
void matrix_print(int n){
for(int i=0; i<n; i++){
for(int l=0; l<n; l++){
cout << a[i][l] << " ";
}
cout << endl;
}
}
} ;
matrix operator + (matrix x, matrix y){
int s;
int n=x.n;
matrix sum;
for(int i=0; i<n; i++){
for(int l=0; l<n; l++){
sum.a[i][l]=y.a[i][l]+x.a[i][l];
}
}
return sum;
}
int main(){
int n;
cin >> n;
matrix o;
o.matrix_input(n);
matrix c;
c.matrix_input(n);
matrix sum;
sum=o+c;
sum.matrix_print(n);
return 0;
}
In your matrix constructor, n = n assigns the parameter to itself. You probably meant this->n = n;. However, it would be better for you to use the member-initialiser list:
matrix(int b[100][100], int n) : n(n)
{
for(int i=0; i<n; i++) {
for(int l=0; l<n; l++) {
a[i][l]=b[i][l];
}
}
}
And your operator + does not set sum.n.
UPDATE
matrix_input() does not modify the matrix's n member either. In other words, your class does not maintain its own invariants. Querying x.n inside operator + is then meaningless.
You should modify matrix so that its member n is always valid and reflects what's in the matrix. You can then drop the parameter n from matrix_print().
And BTW, why do you call your member functions matrix_something? They are already in the scope of matrix. Just input and print would be fine.
Your main error is in the line n=n, which is a self-assignment.
As you can guess this is pretty much a no-op when n is an integer (and should be most of the time). You mean this->n = n;
(better way is to not clash the naming but that small fix will work. You also need to fix operator+ to assign sum.n = n;
The local n parameter takes precedence over the class member so you need this->n to qualify the class member.
Incidentally your matrices are quite large (10,000 ints) so are expensive to copy. So your operator+ overload would be more efficient if it took its parameters as const references.
Presumably n is a logical size, as physically your matrix is always 100 * 100. Your default constructor though should at least initialize n to 0 or subsequent behaviour trying to read this matrix would be undefined. You should possibly put in assertion checks when reading what might be beyond the bounds of your matrices. (Your operator+ could check that both have the same dimension).
If you want to use "dynamic" sizing, so you only use the memory resources you are going to actually use for your matrix, you would implement it a bit differently. I guess that would be a more advanced exercise for your level.
Incidentally it "printing 0 all the time" is random as the behaviour you should get is actually undefined, as x.n (and sum.n in the addition) is an uninitialised variable that you are then reading.