My output for the call to the temporary array size wont correctly output. It resizes as according, but I can't get the MAX to display the new value of the new array. My error is within the Resize function within the class.
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <ctime>
using namespace std;
class VectorClass {
private:
int * Vector;//This will be our resizeable array
int Size; //Keep track of vector current size
int MAX=10;
int growth = 5;
int num;
int Resize(int growth, int MAX);
public:
VectorClass(int growth, int Size);
~VectorClass();
int AddItem(int num);
void RemoveItem();
void Print(void);
};
VectorClass::VectorClass(int growth, int Size)
{
Size = 10;
growth = 5;
Vector = new int[Size];
}
VectorClass::~VectorClass()
{
cout << "Destructor was called." << endl;
}
//Will insert num into the vector at the current open position
int VectorClass::AddItem(int num)
{
Vector[Size] = num;
Size++; //Indicate that there isnt as much free space
if (Size == MAX)
{
Resize(Size, MAX);
}
Print();
return num;
}
//Get rid of the most recently added item
void VectorClass::RemoveItem()
{
Size--; //Tricks the vector into one fewer elements in it it currently does
Print();
}
int VectorClass::Resize(int growth, int MAX)
{
cout << "Array is full! Resizing the Array!" << endl;
//Step 1: make a copy
int * temp = new int[MAX]; //Make a new array, same size as exiting array
//loop that copies the original into the copy
for (int i = 0; i<MAX; i++)
{
temp[i] = Vector[i];
}
//Step 2: Delete the original
delete[] Vector; //Deletes all elements in the array Vector from the Heap
//Step 3: Make a bigger vector
Vector = new int[MAX + growth];
//Step 4: Reverse the copy and record the size change
for (int i = 0; i<MAX; i++)
{
Vector[i] = temp[i];
}
MAX = MAX + growth;
//Step 5: Delete the copy
delete[] temp;
cout << "Resize was called.\n" << endl;
return MAX;
}
void VectorClass::Print()
{
cout << "*******************************************************" << endl;
for (int i = 0; i< Size; i++)
{
cout << Vector[i] << endl;
}
cout << "Size = " << Size << "\tMAX = " << MAX << "\t Growth = " << growth << endl << endl;
cout << "*******************************************************" << endl;
}
int main(void)
{
VectorClass V(5,10);
for (int i = 0; i <= 4; i++)
{
int x = rand();
V.AddItem(x);
}
//Print the Vector #1
V.Print();
//Delete 2 Items
V.RemoveItem();
V.RemoveItem();
//Add 9 random Numbers
for (int i = 0; i <= 8; i++)
{
int x = rand();
V.AddItem(x);
}
//Print the Vector
V.Print();
system("pause");
return 0;
}
Several things are wrong with you code. The first one, probably not the one you care about most, is that you never free the memory. You should do it in your destructor, or even better use a std::unique_ptr to handle your memory.
Now, i believe you are yourself confused about your own variables. I see that you possess a variable member named num that you never use. Even worse, you have a parameter in AddItem with the same name. Are you sure it does what you want? The same is true for growth. I would advise you to name your member variable differently, so that you know what they are quickly. I prefixe them with "m_" for example, but you can do as you wish.
You do not need to declare your function parameters inside your class. Only in the function prototype.
Then, in your AddItem function, you use your variable Size to determine where to add the new element, but you initialize your array with it too, which means that not only you do not add your elements at the beginning of your array, you try to write them in memory you do not own!
I could continue for a long time. I am sorry but it only appears to me that you do not know C++ at all. You should go learn the basics again, and maybe start with an easier project to begin your C++ learning.
Good luck :-)
Related
Hope my question isn't confusing. I'll explain that with code.
I'm learning constructor/desctructor and new/delete in C++. While comparing two piece of code, I'm thinking about where the object and it's members are allocated.
I got a little bit confused when I see the new in constructor and main, and delete in destructor and main:
In the first example, I think local object c is allocated in stack. And that means, members list pointer, two int values (size and capacity) are all in stack. The object also contains an array in size 10, however the array itself is allocated in heap since new is used. When the program ends, the local object c (including the pointer) will be freed automatically. And the array pointed by pointer list will be freed as well, by destructor. Is that correct?
#include <iostream>
#include <string>
using namespace std;
class Collector {
int * list;
int size;
int capacity;
public:
// Default constructor
Collector(){
// We must define the default values for the data members
list = nullptr;
size = 0;
capacity = 0;
}
// Parameterized constructor
Collector(int cap){
// The arguments are used as values
capacity = cap;
size = 0;
list = new int[capacity];
}
bool append(int v){
if (size < capacity) {
list [ size++ ] = v;
return true;
}
return false;
}
// A simple print function
void dump(){
for(int i = 0 ; i < size ; i++) {
cout << list[i] << " ";
}
cout << endl;
}
~Collector(){
cout << "Deleting the object " << endl;
if (size > 0)
delete[] list;
}
};
int main(){
Collector c(10);
for (int i = 0 ; i < 15 ; i++){
cout << c.append(i) << endl;
}
}
Now compared with the second example, object is created with new. So all members including pointer and two int values are all allocated from heap. The array itself is also in heap for the same reason as the first example. Before the program ends, there is a delete so the pointer and two int values are all freed. The array is also freed since the desctructor is called when delete command is issued. Is my understanding correct?
#include <iostream>
#include <string>
using namespace std;
class Collector {
int * list;
int size;
int capacity;
public:
// Default constructor
Collector(){
// We must define the default values for the data members
list = nullptr;
size = 0;
capacity = 0;
}
// Parameterized constructor
Collector(int cap){
// The arguments are used as values
capacity = cap;
size = 0;
list = new int[capacity];
}
bool append(int v){
if (size < capacity) {
list [ size++ ] = v;
return true;
}
return false;
}
// A simple print function
void dump(){
for(int i = 0 ; i < size ; i++) {
cout << list[i] << " ";
}
cout << endl;
}
~Collector(){
cout << "Deleting the object " << endl;
if (size > 0)
delete[] list;
}
};
int main(){
Collector *c;
c = new Collector(10);
for (int i = 0 ; i < 15 ; i++){
cout << c->append(i) << endl;
}
delete c;
cout << "Exiting program" << endl;
}
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));
Here is what I have so far: http://cpp.sh/54vn3
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE); //function prototype resize
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE); //function prototype sortFUNC
int main()
{
int SIZE = 4; //size of current array
int maxSIZE = 10; //size of final array
int *original = new int[SIZE] {5, 7, 3, 1}; //old(current) array
cout << "Elements in array: "; //test output
reSIZE(original, SIZE, maxSIZE); //call function resize
cout << endl << endl; //blank line
cout << "Elements in array in increasing order: "; //test output
sortFUNC(original, SIZE, maxSIZE); //call function sortFUNC
cout << endl << endl;
return 0;
}
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE)//function definition
{
int *temporiginal = new int[SIZE + 3]; //(final)new array
for (int i = 0; i < SIZE; i++) //copy old array to new array
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original; //delete old array
original = temporiginal; //point old array to new array
return temporiginal;
}
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE)
{
for (int i = 0; i < SIZE; i++)
{
int smallest = original[i];
int smallestINDEX = i;
for (int m = i; m < SIZE; m++)
{
if (original[m] < smallest)
{
smallest = original[m];
smallestINDEX = m;
}
}
swap(original[i], original[smallestINDEX]);
}
int *temporiginal = new int[SIZE + 3];
for (int i = 0; i < SIZE; i++)
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original;
original = temporiginal;
}
I want to add a few elements at the end of the array in main, but when I do, the program crashes when I run it. The resize function that I created is supposed to expand the function in main to hold 10 elements. The one in main originally holds 4. The new array is supposed to change that to 10. How do I add three more integers to the array in main without it crashing? Is my resize function wrong? Or is it a problem in my main? The program that is shown right now works as is. But when I add another integer in the array in main, it crashes. Like, if I add a 2 after the 1.
Thanks.
Edit: I was able to add elements at the end of the array in main by adding them in the resize function.
cpp.sh/35mww
Like mentioned earlier, maxSIZE isn't being used. There are more useless stuff as well. I have to clean this up, but I figured out what I was trying to figure out. I don't know how to use structures yet. I know that there are a lot of different ways to write a program. I'm just a beginner.
Thanks, everyone.
You need to modify the value of size everytime you call the function rezise other wise even if u call the function resize 3 times u always will have SIZE+3 on your array size.After call resize try
original[4] = 0;
original[5] = 0;
original[6] = 0;
and after that try to do this.
original[7] = 0;
you should be able to see your mistake
My program is supposed to iterate through an array for as many times as there are hours using only a pointer.
for (int i = 0; i < totalHours; i++)
{
cout << " " << i + 1;
while (ptrSvr <= last)
{
rand_set(ptrSvr);
print(ptrSvr);
ptrSvr++;
}
cout << endl;
}
return 0;
With this being the function for rand_set
void rand_set(int* &ps)
{
*ps = rand() % 10;
}
And this being the function for print.
void print(int* ps)
{
cout << " " << *ps << " ";
}
Once this iterates though, I don't understand how to set the pointer back to the first address in the array so that when i increases, it will print a new row starting at the beginning. Currently, it will only print one row. There's also a catch - I can only use the given pointer to access the array. I cannot use array indices.
Additionally, the highest number randomly generated must be stored in a highestAttempts pointer and when printed, must have a * next to it. This functionality must be included in the rand_set function. I've only gotten it to print a * next to all of them, or it gets printed on the first random number, and on each one if they increase.
Thanks for any advice in advance. I am in a 200 level c++ class, so this should be as simple as possible.
Variables are declared and initialized like so.
void initialize(int ts, int* &ps, int* &pt,
int* &l, int* &ha)
{
for (int i = 0; i < ts; i++)
{
ps[i] = 0;
pt[i] = 0;
l = &ps[i];
}
ha = NULL;
srand(time(NULL));
}
...
// Pointer declarations
int *ptrSvr; // Po
int *ptrTotal; // Po
int *last; // Po
int *highestAttempts; // Po
// Variable declarations
int totalServers; // Va
int totalHours; // Va
int total; // Va
// Prompt user for number of serv
// totalServers and totalHours
cout << "Enter the number of web
cin >> totalServers;
cout << "Enter the number of hour
cin >> totalHours;
// Declares arrays for ptrSvr and
// of total servers
ptrSvr = new int[totalServers];
ptrTotal = new int[totalServers];
if you have something like
int arr [] = {};
then
ptrSvr = arr;
after while loop would reset it. otherwise you have to store the very first value of ptrSvr and reset it after while loop exits
So I am trying to create a custom class that functions like a vector. It is supposed to have a default constructor that creates an empty vector with a capacity of 2, a parameterized constructor with a capacity of n, a destructor, a function to return the size of a vector, the capacity of a vector, a function to delete the data and reset a vector to capacity 2, a push_back function to put n at the end of a vector, and a function to return the value stored at n. I have the majority of the code written out, but I am receiving errors on the driver.cpp file whenever I try to use the .capacity() function to show the capacity of the "vector". Errors are
too few arguments in function call' and Vector::capacity: function
does not take 0 arguments
every time I try to use capacity() in driver.cpp. Please help
//Vectors.h
#include "stdafx.h"
#include "driver.h"
#include "targetver.h"
#include <iomanip>
#include <array>
#include <stdio.h>
#include <tchar.h>
#include <string>
using namespace std;
class Vector
{
double* arr; // pointer to the first element of this myvec
int cap; // number of elements arr can hold (i.e. size of underlying array)
int n; // size of this myvec
int sz = 1;
// Increases the capacity of the underlying array to be sz. If sz
// is smaller than the current capacity then nothing is done.
// create an empty vector
void increase_capacity(int sz)
{
if (sz <= cap) return;
double* new_arr = new double[sz]; // allocate a new array
for (int i = 0; i < cap; ++i)
{ // copy old vector into new one
new_arr[i] = arr[i];
}
cap = sz; // set the new capacity
delete[] arr; // delete the old vector
arr = new_arr;
}
public:
Vector()
{
arr = new double[sz];
}
Vector(int n)
{
arr = new double[n];
}
int size() const
{
return n;
}
void push_back(double x)
{
if (n >= cap) increase_capacity(2 * cap);
arr[n] = x;
++n;
}
double capacity(int i, double val)
{
if (i < 0 || i >= n) cout << ("range error");
arr[i] = val;
return val;
}
double at(int n) const
{
if (n < 0 || n >= n) cout << ("range error");
return arr[n];
}
void clear()
{
delete[] arr;
Vector();
}
~Vector()
{ // destructor
delete[] arr;
}
};
//driver.cpp
const int TEST_VALUE1 = 21;
const int TEST_VALUE2 = 31;
const int TEST_VALUE3 = 41;
const int MAX = 12;
int main( )
{
// Create a default vector
Vector sam;
// push some data into sam
cout << "\nPushing three values into sam";
sam.push_back(TEST_VALUE1);
sam.push_back(TEST_VALUE2);
sam.push_back(TEST_VALUE3);
cout << "\nThe values in sam are: ";
// test for out of bounds condition here
// and test exception
for (int i = 0; i < sam.size( ) + 1; i++)
{
try
{
cout << sam.at(i) << " ";
}
catch(int badIndex)
{
cout << "\nOut of bounds at index " << badIndex << endl;
}
}
cout << "\n--------------\n";
// clear sam and display its size and capacity
sam.clear( );
cout << "\nsam has been cleared.";
cout << "\nSam's size is now " << sam.size( );
cout << "\nSam's capacity is now " << sam.capacity() << endl;
cout << "---------------\n";
// Push 12 values into the vector - it should grow
cout << "\nPush 12 values into sam.";
for (int i = 0; i < MAX; i++)
sam.push_back(i);
cout << "\nSam's size is now " << sam.size( );
cout << "\nSam's capcacity is now " << sam.capacity( ) << endl;
cout << "---------------\n";
cout << "\nTest to see if contents are correct...";
// display the values in the vector
for (int i = 0; i < sam.size( ); i++)
{
cout << sam.at(i) << " ";
}
cout << "\n--------------\n";
cout << "\n\nTest Complete...";
cout << endl;
system("PAUSE");
return 0;
}
Here are the requirements for my class, of which are relevant:
A default constructor that creates a vector that is empty. Its size will be zero and its capacity will be two. Remember that size refers to the number of elements currently stored in the vector.
A parameterized constructor that creates a vector of capacity n. Its size will initially be zero.
A function size( ) that returns the size of your vector. The size is defined as the number of integer values that have been stored in the vector. The size will change as integer values are added.
A function capacity( ) that returns the capacity of the vector. The capacity is defined as the number of integer values that can be stored in the vector. The capacity changes when the vector grows.
Your defined capacity method takes two arguments, the way you've made it. It probably shouldn't, because as you are trying to use it, it should be purely dependent on the object and just return the value you want. You have the choice between providing arguments: Vector::capacity(i, var), or changing your definition to accept 0 arguments.
From what I understand about the actual Vector class method capacity() in C++, you shouldn't be taking any arguments. However, from what I understand about your definition of capacity, you're modifying a component, which you do need to supply both a float and an int, which you are not doing when you write Vector::Capacity().
The first part of your code seems strange (preceding public:), since it is not a constructor but you seem to be initializing a vector. Also, your variable sz should be renamed to cap, since it is the capacity, not the size, and your variable n to sz since it is the size.. (I understand why you are confused...)
To keep things easy for myself I changed the double* to a double. Feel free to change it back. I also wrote sz as size because two letters make it a lot prettier to look at.
class Vector
{
// initialise array myvec in constructors.
int cap; // number of elements arr can hold (i.e. size of underlying array)
int size; // size of this myvec (same as n)
At this point, there is no use to "create an empty vector" outside of a constructor. Therefore I moved the bit here into the two constructors.
public:
Vector()
{
double[2] arr; //creates an array of size two, that is empty.
cap = 2;
size = 0;
}
Vector(int n)
{
double[n] arr; //creates an array of size n, also empty.
cap = n;
size = 0;
}
int size() const
{
return size;
}
void push_back(double x)
{
if (size >= cap) increase_capacity(2 * cap);
arr[size] = x;
++size;
}
double capacity()
{
return cap;
}
The rest of the functions seem ok. Note that I may not have gotten the memory management right, especially with the constructor. If I did, I was bound to get it wrong. I hope you can figure that out.
EDIT: After looking at the pushback method, I now see why you had the increase_capacity method. Here's an edit relative to my code:
void increase_capacity(int new_cap)
{
//if (sz <= cap) return; THIS IS NOT NEEDED, since the function is only called when size > cap.
double[new_cap] arr; // allocate a new array - Note that once again I'm not using pointers, you may want to change this.
for (int i = 0; i < cap; ++i)
{ // copy old vector into new one
new_arr[i] = arr[i];
}
cap = new_cap; // set the new capacity
delete[] arr; // delete the old vector
arr = new_arr;
}