Some test cases aren't passing - c++

#include <iostream>
#include <vector>
int i=0; //points at the current stack that we are working with
int box=0; //no. of boxes held by the crane
int64_t H; //max. height of the stacks given in the que.
int main()
{
int n, value; //storing no. of stacks and creating an additional variable value to store operations
std::cin>> n >> H;
int64_t arr[n]; //storing the no. of boxes each stack has in an array
std::vector<int> arr2; //storing the operations we have to perform in a vector
for(int j=0; j<n; j++){std::cin>> arr[j];} //getting arr
while(std::cin>>value) //getting arr2
{
arr2.push_back(value);
}
for(int xy=0; xy<n; xy++){if(arr[xy]>H){return 0;}} //ensuring that all stacks have no.of boxes less than max. height
if(arr2.size()<1 || arr2.size()>10e5 || n<1 || n>10e5 || H<1 || H>10e8){return 0;} //constraints given in the que.
int k=0; //creating a variable to keep count of how many programs we have already executed
while(k<arr2.size()){
if(arr2[k] == 1){MoveLeft();}
else if(arr2[k]==2){MoveRight(n);}
else if(arr2[k]==3){PickBox(arr, i);}
else if(arr2[k]==4){Dropbox(arr, i);}
else if(arr2[k]==0){k=arr2.size();}
k++;
}
for(int j=0; j<n; j++){std::cout<< arr[j] << " ";} //printing the arr after executing the code
return 0;
}
This is a question from a past year ZCO. And the above code is what I wrote to solve the prob.
The four functions Moveleft, MoveRight, Pickbox, Dropbox have been defined in the same file but aren't shown here because I think there's no issue with them.
When I submit the code, all test cases passed except 2. I don't know what is the problem with my code. Pls help me.
I have tried my best to make the code readable. Sorry if the code looks messy.

With the method you're trying to define an array with a user-input length is unfortunately invalid in C++.
But fortunately, there are basically two methods use to allocate arrays dynamically.
Method 1: Using Vectors
Vector is an important part of C++. It has a lot of features (e.g. its size don't need to be defined static unlike a normal array does, can redefine array size, etc.) An example's given:
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> vArray; // vector<> declaration
int size = 0;
int getInput = 0;
std::cout << "Enter an array size: ";
std::cin >> size;
for (int i = 0; i < size; i++) {
std::cout << "Enter a value: ";
std::cin >> getInput;
vArray.push_back(getInput); // inserts one+ container and data in it
}
for (int i = 0; i < vArray.size(); i++) {
// retrieving contained data...
std::cout << vArray[i] << std::endl;
}
return 0;
}
Method 2: Using 'new' Keyword with Pointed Variable
The simple use of new will help you to achieve your requirement. It's less recommended since already there's concept of vectors which actually works efficiently than arrays. Let's take a look into a simple program:
#include <iostream>
int main(void) {
int *pArray;
int size;
std::cout << "Enter an array size: ";
std::cin >> size;
pArray = new int[size]; // initializing array with dynamic size
for (int i = 0; i < size; i++) {
std::cout << "Enter value: ";
std::cin >> pArray[i];
}
for (int i = 0; i < size; i++) {
std::cout << pArray[i] << std::endl;
}
delete[] pArray;
return 0;
}
Both are nice options to work with, but it's recommended by most using vector<>.

Related

How to display a dynamic array with a for loop in c++

I am trying to display a dynamic array to check my inputs using a for loop and without any vector (I'm still a beginner so I don't know what it means yet and it's a class assignment). I am also trying to implement classes and objects. Here's my code:
#include <iostream>
using namespace std;
class Set {
private:
int size;
int* arr = new int[size];
public:
void setArr();
void dispArr();
};
void Set::setArr() {
cout << "Please enter the size of your array: ";
cin >> size;
cout << "\nPlease enter the elements of your array: ";
for (int i = 0; i < size; i++)
cin >> arr[i];
}
void Set::dispArr() {
for (int j = 0; j < size; j++)
cout << arr[j] << "\t";
}
void main()
{
Set myArray;
myArray.setArr();
myArray.dispArr();
}
When I run the code, sometimes it works, but most of the time, it throws a breakpoint error without any error code or explanation. Could someone help me figure out how to combine dynamic arrays and classes?
Please and thank you.
You are allocating arr before you initialise size. As a result, size has an indeterminate value at that point which explains your program's unpredicatable behaviour.
Solution: allocate arr after reading size. Better yet, use std::vector.

Run-Time Check Failure #2 - Stack around the variable 'sortObject' was corrupted. how to fix?

I was trying to store numbers in an array. The first half of the array are numbers that are ascending 1,2,3,4,5 etc and the second half of the array are random numbers. When i run the program it produces the output I wanted but gives me the error please help
#include <iostream>
#include <cstdlib>
using namespace std;
class sorting {
private:
int size, elements;
int arr[NULL];
public:
void sort(){
cout << "Enter number of desired elements" << ">"; cin >> elements;
arr[elements];
half();
}
void half() {
for (int i = 0; i < elements/2; i++) {
arr[i] = i + 1;
}
for (int i = elements / 2; i < elements; i++) {
arr[i] = rand();
}
cout << "This is the elements of the array";
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
}
};
int main()
{
sorting sortObject;
sortObject.sort();
return 0;
}
As i could see you want the array size to change during run time depending on the input, we need to dynamically allocate a array.so take a integer pointer as a field instead of static array.
then inside the sort function after reading the input, dynamically allocate the memory to pointer.(actually its better if we do it in a constructor).
int *arr;
arr=(int *)malloc(elements*sizeof(int));

How to initialize an array in a constructor c++

I need help with this code.
What I want is to make a parametric constructor and initialise/set the value of array in it.
Question: Make a class with arrays of integers and initialise it in a constructor. Then find the smallest and largest numbers using functions.
But I am stuck at how to initialise the array in the constructor.
I want to take data input in both ways
(1) By user, using cin
(2) By giving my own values
class Numbers
{
int Arr[3];
public:
Numbers() //default constructor
{
for (int i=0 ; i<=2 ; i++)
{
Arr[i]=0;
}
}
Numbers(int arr[]) //parameteric constructor
{
for (int i=0;i<=2;i++)
{
Arr[i]=arr[i];
}
}
};
int main()
{
int aro[3] = {0,10,5};
Numbers obj (aro);
return ;
}
The solution is pretty simple. I've made a new program from start again (for sake of understanding). According to your requirement, you wants to get input of array elements from the user dynamically and assign them to a constructor and use a method to print the highest value.
Consider the following code:
#include <iostream>
using namespace std;
const int N = 100;
class Numbers
{
int largest = 0;
public:
Numbers(int, int[]);
void showHighest(void)
{
cout << largest << endl;
}
};
Numbers::Numbers(int size, int arr[])
{
for (int i = 0; i < size; i++)
{
if (arr[i] > largest)
{
largest = arr[i];
}
}
}
int main(void)
{
int arrays[N], total;
cout << "How many elements? (starts from zero) ";
cin >> total;
for (int i = 0; i < total; i++)
{
cout << "Element " << i << ": ";
cin >> arrays[i];
}
Numbers n(total, arrays);
n.showHighest();
return 0;
}
Output
How many elements? (starts from zero) 3
Element 0: 12
Element 1: 16
Element 2: 11
16
Note: I've initialized a constant number of maximum elements, you can modify it. No vectors, etc. required to achieve so. You can either use your own values by removing the total and its followed statements and use only int arrays[<num>] = {...} instead. You're done!
Enjoy coding!
I suggest to use std::vector<int> or std::array<int>.
If you want initialize with custom values you can do std::vector<int> m_vec {0, 1, 2};
Thank you so much for your help. I was basically confused about how to use arrays in a constructor and use setters/getters for arrays in a class. But you all helped a lot. Thanks again.
Numbers(int arr[])
{
for (int i=0;i<=9;i++)
{
Arr[i]=arr[i];
}
Largest=Arr[0];
Smallest=Arr[0];
}
void Largest_Number()
{
header_top("Largest Number");
Largest=Arr[0]; //Using this so we make largest value as index zero
for (int i=0 ; i<=9 ; i++)
{
if(Arr[i]>Largest)
{
setLargest( Arr[i] );
}
}
cout<<"Largest Number: "<<getLargest()<<endl;
}

Trying to get user data in an array

OK I'm still a beginner, and i have alot to learn. Still in my first programming class and was wondering if i could get some help on an assignmet. I DON'T WANT YOU TO DO IT FOR ME just some help. I'm supposed to making a lottery type game using arrays and functions. Here's what i have so far:
#include<iostream>
#include<random>
#include<ctime>
using namespace std;
void getPlayersNumbers(int playerArray[], int size);
void getComputersNumbers(int computerArray[], int size);
bool WinningNumber(int playerArray[], int computerArray[], int size);
int main() {
const int SIZE = 5;
int userNumbers[SIZE];
int computerNumbers[SIZE];
getComputersNumbers(computerNumbers, SIZE);
return 0;
}
void getPlayersNumbers(int playerArray[], int size) {
int playersNumbers;
cout << "Please enter 5 numbers for a chance to win!!\n";
for (int i = 0; i < size; i++) {
cin >> ???
}
}
void getComputersNumbers(int computerArray[], int size) {
mt19937 randomGenerator(time(0));
uniform_int_distribution<int> randomNumbers(1, 5);
int computerNumbers;
for (int i = 0; i < size; i++) {
computerNumbers = randomNumbers(randomGenerator);
computerArray[i] = computerNumbers;
cout << computerNumbers << " ";
}
cout << endl;
}
bool winningNumbers(int playerArray[], int computerArray[], int size) {
}
My getComputerNumbers function is working just fine. The one I'm having trouble with is my getPlayerNumbers function. How would i go about getting the uses numbers from them, and keeping them so when i call the function i can compare them to the random numbers in my getComputerNumbers function? Now i already know how I'm going to go about comparing the numbers. That's what my that third function winningNumbers is for. I just Need help with the getPlayersNumbers.
Also if you see anything else that i can do to make this code better let me know.
Thanks again!!
If you want to store user's number into an array:
for (int i = 0; i < size; i++) {
cin >> userNumbers[i]
}
when you want to access a particular number out of the five, you use:
userNumbers[n], where n ranges from 0 to 4
Just do:
void getPlayersNumbers(int* playerArray, int size)
{
cout << "Please enter 5 numbers for a chance to win!!\n";
for (int i = 0; i < size; i++) {
cin >> playerArray [i];
}
}
Thanks to #user4581301 for pointing out a better solution using std::vector
std::vector getPlayersNumbers(int size)
{
std::vector myNumberList;
cout << "Please enter 5 numbers for a chance to win!!\n";
for (int i = 0; i < size; i++) {
int number;
cin >> number;
myNumberList.push_back (number);
}
return myNumberList;
}
STL makes working with arrays a whole lot easier and also it provides additional functions that are optimized for their use case

Heap Corruption Error while doing bubble sort using dynamic arrays

Hi i am trying to create a bubble sort using dynamic arrays, the code seems to work but throws an run time error : HEAP Corruption Detected(since i am deleting dynamic arrays in the ...i donot understand why i am getting such an error). Also, the last two elements in the given array get sorted but i get the address displayed for the last element . As i am trying to learn dynamic arrays on my own.Kindly help me understand the error. Thanks in advance !!!
Array = {125,12,2,36,19}
#include "stdafx.h"
#include <iostream>
using namespace std;
void bubblesort(int* a, int length); // for bubble sort//
int _tmain(int argc, _TCHAR* argv[])
{
int size;
cout << " enter the size of array: " << endl;
cin >> size;
int* a = new int[size];
cout << "enter the elements in an array: " << endl;
for (int i = 0; i < size; i++)
cin >> *(a+i);
bubblesort(a, size);
delete[] a;
a = NULL;
return 0;
}
void bubblesort(int* a, int length)
{
int temp = 0;
for (int i = 0; i < length; i++)
{
if (a[i] > a[i+1])
{
temp = a[i+1];
a[i+1] = a[i];
a[i]= temp;
}
}
for (int i = 0; i < length; i++)
{
cout << " The elements are : " << endl;
cout << a[i] << endl;
}
}
As (it was) mentioned in the comments, you're reading outside the array.
a[i + 1] = a[i]; //When i == length - 1, this is UB
In the last iteration of the for loop, you'll overwrite whatever is after the end of the array. An array a[length] is only valid from 0 through length - 1.
Also, your bubble sort only runs once, while it is supposed to constantly run until all items are sorted.
On a subjective note, *(a+i) is identical to, but less readable than, a[i].