Below is my current code for my latest assignment and I cannot figure out what the problem is printing the array. Forgive me for the crappy code, in my class we were thrown into C++ and none of us have ever used it before so it may be a simple mistake but no one in the house can help me.
Header file DynamicArray.h:
//
// DynamicArray.h
///#include <rpcndr.h>
#ifndef DYNAMIC_DYNAMICARRAY_H
#define DYNAMIC_DYNAMICARRAY_H
#endif //DYNAMIC_DYNAMICARRAY_H
// union
// intersection
// relative complement
// insertion - if the element is already in the set, then nothing happens
// deletion - if the element is not in the set, then nothing happens
// query to check whether an element is in a set
// query to find the number of number of elements in a set
// display the set
//destructor
// copy constructor
// ***********************************overloading assignment operator***************************************************
class DynamicArray{
public:
DynamicArray(int size);
DynamicArray(const DynamicArray &original, int Size);
/// DynamicArray(int Size);
~DynamicArray();
void Union();
void Intersection();
void Complement();
int Insert(int position, int entry, int size);
int Delete(int position, int entry, int size);
bool Qelement(int size, int entry);
int Qset(int size);
int size = 20;
int *array;
};
//
//
//
Source file DynamicA.cpp- here I define the constructors and member functions:
//
// DynamicA.cpp
//
//Union();
//Intersection();
//Complement();
//Insert();
//Delete();
//Qelement();
//Qset();
#include <iostream>
#include "DynamicArray.h"
using namespace std;
DynamicArray::DynamicArray(int &size = 30){
size = 20;
*array = new int[size];
for(int i = 0; i < size; i++){
array[i] = 0;
};
}
/// DynamicArray::DynamicArray(int Size) {
///
/// }
DynamicArray::DynamicArray(const DynamicArray &original, int size) {
size = original.size;
array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = original.array[i];
}
}
DynamicArray::~DynamicArray(){
delete[] array;
}
void DynamicArray::Union(){
}
void DynamicArray::Intersection() {
}
void DynamicArray::Complement(){
}
int DynamicArray::Insert(int position, int entry, int size) {
if(!Qelement()){
for(int i = size+1; i > position+1; i--){
array[i] = array[i-1];
}
array[position] = entry;
}
}
int DynamicArray::Delete(int position, int entry, int size){
for(int i = 0; i < size; i++){
if(array[i] == entry) {
for(int x = i; x < size; i++){
array[x] = array[x+1];
}
size--;
}
}
}
bool DynamicArray::Qelement(int size, int entry) {
for(int i = 0; i < size; i++){
if(array[i] == entry){
return true;
}
}
}
int DynamicArray::Qset(int size){
return size;
}
main.cpp - this is where my issue is. The error I continue to receive is that dArray is not an array.
//main.cpp
#include <iostream>
//#include <DynamicArray.h>
#include "DynamicArray.h"
//#include "DynamicA.cpp"
//using namespace std;
int main() {
DynamicArray dArray();
for(int i = 0; i < array; i++) {
cout << dArray[i];
}
}
Your class DynamicArray is not an array, the compiler has it right. It's just a class you've defined. For your code to work, you need to overload DynamicArray::operator[](int), for example, like so:
#include <cassert>
int DynamicArray::operator[](int idx)
{
assert(idx < size);
return array[i];
}
The reason is that operator[] is only defined for the built-in array type, where it has an established meaning and understood by the compiler. But you have defined an arbitrary class, and your understanding that it is an array is only your understanding, i.e. an assumption, which in no way is perceived by the compiler, so to say.
Now, let me point this one out before you run into issues caused by that mistake: the fields size and array must be private or at least protected! Read up on encapsulation in C++, as well as the other two or three founding principles of this language. You may wonder how to access the size of the array form the outside given this change, well that's where the so-called getter-setter methods come into play. Define int DynamicArray::size() const { return size; } to let the array tell its size to its clients.
Now you can use the previously defined operator[](int) with int size():
DynamicArray myArray(5);
for(int i = 0; i < myArray.size(); ++i)
std::cout << myArray[i] << " ";
Other errors: two pointed out by#crashmstr: *array = new int[size]; should be array = new int[size]; and DynamicArray myArray(); isn't going to build, since this calls the undefined default constructor.
Related
I keep receiving the error listed above for my methods. Here is the relevant code:
BubbleSort<int> bs;
analysis << "Working with Bubble Sort with " << size << " random elements\n";
start = clock();
for(int i=0;i<=size;i++)
{
bs.sort(array[size], 1+(rand() )); --> error
}
Here is my header file:
#ifndef BUBBLESORT_H_
#define BUBBLESORT_H_
#include <iostream>
using namespace std;
template <class Type>
class BubbleSort
{
private:
public:
int array[], size;
Type sort(Type array[], Type size);
};
template<class Type>
Type
BubbleSort<Type>::sort(Type array[], Type size)
{
int i, j, flag = 1;
int num_cmps = 0;
int temp;
for (i = 1; (i <= size) && flag; i++)
{
flag = 0;
for (j = 0; j < (size - 1); j++)
{
if(array[j+1] < array[j])
{
temp = array[j];
++num_cmps;
array[j] = array[j+1];
++num_cmps;
array[j+1] = temp;
++num_cmps;
flag = 1;
++num_cmps;
}
}
}
}
#endif
Previously I had asked the user for the number of elements and then cin >> size;. I thought this would make size constant, which is what my research has told me is the problem with this error. Any help would be greatly appreciated.
Problem 1
In BubbleSort, instead of
Type sort(Type array[], Type size);
You need something like:
Type sort(Type array[], size_t size);
Problem 2
When you call the function,
array[size] evaluates to an int, not an array. Use:
bs.sort(array, size);
bs.sort(array[size], 1+(rand() ));
The function sort requires an array, but you are passing the item in array at index size (possibly out of bound)
I have a class that needs to store an array with a variable size. Ideally, this size would be defined as a parameter given to the constructor of the class.
I can define a constant and then work with that, as seen below:
#include <iostream>
#define ARRSIZE 5
class Classy{
private:
int myarray[ARRSIZE];
public:
Classy();
void printarray();
};
Classy::Classy(){
for(int i = 0; i < ARRSIZE; i++){
myarray[i] = i * i * 2;
}
}
void Classy::printarray(){
for(int i = 0; i < ARRSIZE; i++){
std::cout << myarray[i] << std::endl;
}
}
However, I'd like to do it like this:
#include <iostream>
class Classy{
private:
int arraysize;
int myarray[arraysize];
public:
Classy(int parraysize);
void printarray();
};
Classy::Classy(int parraysize){
arraysize = parraysize;
for(int i = 0; i < arraysize; i++){
myarray[i] = i * i * 2;
}
}
void Classy::printarray(){
for(int i = 0; i < arraysize; i++){
std::cout << myarray[i] << std::endl;
}
}
The compiler really doesn't like my approach though, so I am looking for an alternative way of doing things.
I did some googling on the subject, but my searches did not come up fruitful. I found this approach which does it using dynamic memory allocation. This is something I'd like to avoid, so I am looking for a solution that does not rely on that. It might well be (and I'm starting to think) that it is the only elegant solution to my problem (and if this is the case, the question should of course be closed as duplicate).
It is required to use dynamic allocation, because sizeof (Classy) must be a compile-time constant. There's no way for your object's internal size to grow. But dynamic allocation doesn't have to be as complicated as that link suggests.
You can do it like this:
#include <memory>
class Classy
{
private:
int arraysize;
std::unique_ptr<int[]> myarray;
public:
Classy(int parraysize);
void printarray();
};
Classy::Classy(int parraysize)
: arraysize{parraysize}
, myarray{new int[arraysize]}
{
for(int i = 0; i < arraysize; i++){
myarray[i] = i * i * 2;
}
}
#include <iostream>
void Classy::printarray()
{
for(int i = 0; i < arraysize; i++){
std::cout << myarray[i] << std::endl;
}
}
This will allow the size to vary at the moment of creation, and be fixed thereafter. std::unique_ptr will take care of automatically destroying the array contents when your object is dying.
You want to use templates to solve this problem:
#include <array>
template<std::size_t ArraySize>
class Classy final
{
public:
static const std::size_t size = ArraySize;
/* The rest of your public interface here */
private:
std::array<int, ArraySize> m_array;
};
Then you can use your class like this:
int main()
{
Classy<5> hasArrayOfFiveElements;
return 0;
}
You could very well opt to not use std::array, in preference for a c-style array. But we're writing C++, so let's use the better language facilities we have available to us :)
Well, I think you can't do it without using dynamic memory allocation while using a classic array, but you can use std::vector. You can do it like this:
#include <iostream>
class Classy{
private:
int arraysize;
std::vector<int> myArrayOfInts;
public:
Classy(int parraysize);
void printarray();
};
Classy::Classy(int parraysize){
arraysize = parraysize;
for(int i = 0; i < arraysize; i++){
myArrayOfInts.push_back(i * i * 2);
}
}
void Classy::printarray(){
for(int i = 0; i < myArrayOfInts.size(); i++){ //you could also use arraysize, but then you
std::cout << myArrayOfInts[i] << std::endl;//must update it when you add or remove any
} // element from vector
}
You need to dynamically allocate your array using new[] and then delete[] it in your destructor. Alternatively, use a std::vector<int> and reserve the amount passed to the constructor. Yet one more method is to make your class templated, taking a size_t argument for the amount of elements you want it to have, but that completely removes the dynamic aspect of it (and you might as well be using std::array at that point.
I know you'd like to avoid dynamic allocation, but it's the most efficient way to do what you want (because vector might take up more space than you expect).
A bit late. However, this may be another approach.
#include <iostream>
#include <cstddef>
class Classy
{
public:
Classy();
template <size_t ARRSIZE>
Classy(int (&arr)[ARRSIZE], size_t size = 0);
void printarray();
private:
int* myarray;
size_t max_size;
size_t arraysize;
};
template <size_t ARRSIZE>
Classy::Classy(int (&arr)[ARRSIZE], size_t size)
{
myarray = arr;
max_size = ARRSIZE;
arraysize = size;
}
void Classy::printarray(){
for(int i = 0; i < max_size; i++){
std::cout << i << " " << myarray[i] << std::endl;
}
}
int main()
{
int arr[10];
Classy c(arr);
c.printarray();
return 0;
}
My weekend assignment was to make a function that gets an array of integers and the size of the array, and creates an array of pointers so that the pointers will be sorted using bubble sort (without changing the original array).
While debugging I found out that it works just fine, but when the function goes back to main() the pointers array gets initialized and everything's gone.
#include <iostream>
using namespace std;
void pointerSort(int arr[], int size, int* pointers[]);
void swap(int a, int b);
void main()
{
int arr[5]={7,2,5,9,4};
int size = 5;
int* pointers[5];
pointerSort(arr, size, pointers);
for (int i = 0; i < 5 ; i++)
cout << *pointers[i] << endl;
}
void pointerSort(int arr[], int size, int* pointers[])
{
int j, i;
bool change = true;
pointers = new int*[size];
for (i = 0; i < size; i++)
pointers[i] = &arr[i];
i = 0;
j = 1;
while (i <= size-1 && change == true)
{
change = false;
for (i = 0; i < size-j; i++)
{
if (*pointers[i] > *pointers[i+1])
{
swap(pointers[i], pointers[i+1]);
change = true;
}
}
j++;
}
}
void swap(int&a, int&b)
{
int temp;
temp = a;
a = b;
b = temp;
}
pointers = new int*[size];
At this point pointers is already an array of pointers, no allocation is needed.
After this line pointers IS NO LONGER THE ARRAY IN YOUR MAIN FUNCTION.
This is why your function is failing, because you are reassigning the array to which pointers is pointing to. The original array ISNT getting reinitialized, its just ignored throughout the entire code.
It is also a memory leak as ATaylor mentions, since you do not delete the allocated space, and cannot delete the space after the function finishes.
To fix everything: just remove the above line.
I am getting a crash error at run time and not sure what exactly to do with the function or how to get the data for it.
FUNCTION DETAILS
Write a function that accepts an int array and size as arguments, then create a new array that is one element bigger than the given. Setting the first element to 0, then copying over what is in the argument array to the new array.
MAIN DETAILS
Use in a program reading int n from input, then read int n from file data name data
passing it to element shifter, then printing it to output (one per line).
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
int main() {
fstream infile;
infile.open("D:\\data.txt");
int n, x;
infile >> x;
cout << "size of array: ";
cin >> n;
const int ARRAY_SIZE = n + x;
int elements[ARRAY_SIZE];
element_shift(elements, ARRAY_SIZE);
system("PAUSE");
return EXIT_SUCCESS;
}
First of all ARRAY_SIZE declared in the main function is not a constant variable but defined at run-time depending on user inputs. This means that the array elements should be created dynamically. On the other hand you read some x variable which is only used to define the size of the array and didn't initialized the array at all. I guess that the problem statement is to read the size of the array from the input, then the data of the array from the file.
There are also lot of mistakes in element_shift function.
Your code should look like something similar to this:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
void element_shift(int* elmts, int size)
{
int new_size = size + 1;
int* shifter = new int[new_size];
shifter[0] = 0;
for(int i = 0; i < size; ++i)
{
shifter[i + 1] = elmts[i];
}
delete [] elmts;
elmts = shifter;
}
int main()
{
fstream infile;
infile.open("D:\\data.txt");
int n;
cout << "size of array: ";
cin >> n;
int* elements = new int[n];
for (int i = 0; i < n; ++i) {
infile >> elements[i];
}
element_shift(elements, n);
for (int i = 0; i < n; ++i) {
std::cout << elements[i] << std::endl;
}
return EXIT_SUCCESS;
}
First off, you spend alot of time creating the shifted array but don't return it back.
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
The elmt_sft pointer is never assigned. You are trying to access memory that is not there by using *elmt_sft. This may be causing your error. Also this function has no way of returning the new array shifter because that variable is locally declared and will disappear once the function exits. If you want to create something new in the function and still have it in memory once the function exits, I recommend creating the array dynamically and returning a pointer to it.
This is untested but should start you in the right direction. It will return a separate dynamically allocated array that will not override your other one.
int* element_shift(int elmts[], int size) {
int *result_array = new int[size + 1]; //dynamically create new array MAKE SURE TO DELETE
result_array[0] = 0; //set 0 index to 0
for (int i = 1; i < size + 1; i++)//start at 1 of the result and put value in
{
result_array[i] = elmts[i - 1];
}
return result_array; //returning pointer
}
I have a header, and a cpp file I was attempting to build.
.cpp file:
#include "SelectionSort.h"
void SelectionSort::Fill(){
Buffer = new char[Size];
for(int i=0;i<Size;i++){
Buffer[i] = rand() % 10;
}
}
void SelectionSort::PrintOut(){
for(int i=0;i<Size;i++){
cout<<Buffer[i]<<endl;
}
}
void SelectionSort::Sort(){
int lowest;
for(int i=0;i<Size;i++){
lowest=i;
for(int j=i;j<(Size-i);++j)
if(Buffer[j]>lowest) lowest = j;
swap(Buffer[lowest], Buffer[i]);
}
}
.h file:
#ifndef SELECTIONSORT_H
#define SELECTIONSORT_H
#include <algorithm>
#include <stdlib.h>
#include <iostream>
using namespace std;
class SelectionSort {
public:
SelectionSort();
SelectionSort(int S){Size= S;}
void Fill();
void PrintOut();
void Sort();
private:
int Size;
char * Buffer;
};
#endif /* SELECTIONSORT_H */
But I get these errors:
SelectionSort.cpp:17: multiple definition of 'SelectionSort::PrintOut()'
SelectionSort.cpp:17: first defined here
SelectionSort.cpp:23: multiple definition of 'SelectionSort::Sort()'
SelectionSort.cpp:23: first defined here
SelectionSort.cpp:10: multiple definition of 'SelectionSort::Fill()'
SelectionSort.cpp:10: first defined here,
How am I defining my functions incorrectly?
I am using netbeans and their generic make/build settings. I've been meaning to get more into make files, should i try to write my own and solve the problem?
Once you get your code to compile, you have a number of logical mistakes (see comments):
void SelectionSort::Sort()
{
int lowest;
for(int i = 0; i < Size; i++)
{
lowest = i;
for(int j = i; j < (Size - i); ++j) // j should terminate at the end of Buffer, not one before the end
if(Buffer[j] > lowest) lowest = j; // comparing a data element to an index, comparison operator reversed
swap(Buffer[lowest], Buffer[i]);
}
}