Member Class Functions - c++

So I am trying to figure out how to create a function that Returns an Array of all integers that are in common with self and ary and returns an empty Array if there are no intersections. This is what I have so far:
IntArray* findIntersections(IntArray &ary) {
int length1 = ary.getLength(); // Getting the length of &ary.
int length2 = getLength([//Right here, there's something to do with "this" because I've created a mArray already and defined it, but I'm not sure how to re-call it here.]); // Getting the length of self.
int length4 = 0; // Because anarchy
if (length1 > length2){ // An if statement to match length4 with the longest array.
length4 = length2;
} else {
length4 = length1;
}
IntArray* newArray; // New IntArray on the heap.
newArray = new* int[length4];
int k = 0;
for (int j = 0; j < length1; j++){ // Two for loops getting the iterator on the same page.
for (int i = 0; i < length2; i++){
if (ary.get(j) == [//The this from earlier, whatever it is][i]){ // Checking to see if digits match each other.
newArray[k] = (ary[j]); // Writing the digit into the NewArray.
k++; // Adding one to the k count to progress the the iterator.
}
}
}
return newArray;
}
In the end, there I know there's gonna be three arrays. The one being passed in, the one being created and passing out, and then that this reference which I honestly don't even know what it is. I'm thinking it's an mArray I created earlier, but I'm not exactly sure. Any help on this would be absolutely fantastic!
Also, here's my .hpp file:
class IntArray {
private:
int *mArray;
int mSize;
public:
IntArray(int *array, int size);
int get(int index);
int getLength();
int indexOf(int value);
bool remove(int index);
IntArray* findIntersections(IntArray &ary);
bool isSubsequence(IntArray &ary);
~IntArray();
};
And my .cpp file:
#include "IntArray.hpp"
IntArray::IntArray(int *array, int size) {
int *newArray = new int [size];
for (int i = 0; i < size; i++){
newArray[i] = array[i];
}
}
int IntArray::get(int index) {
return mArray[index];
}
IntArray::~IntArray() {
delete[] mArray;
}
int IntArray::getLength() {
return mSize;
}
int getLength(int *array){
int length = (sizeof(array)/sizeof(array[0]));
return length;
}
int indexOf(int *array, int value){
int length = getLength(array);
for (int i = 0; i < length; i++){
if (value == array[i]){
return i;
}
}
return -1;
}
bool remove(int *array, int index){
int length = getLength(array);
if (0 <= index && index < length){
for (int i = index + 1; i < length; ++i){
array[i - 1] = array[i];
}
for (int i = 0; i < length; i++)
return true;
} else {
return false;
}
}
IntArray* findIntersections(IntArray &ary) {
int length1 = ary.getLength(); // Getting the length of &ary.
int length2 = getLength([//Right here, there's something to do with "this" because I've created a mArray already and defined it, but I'm not sure how to re-call it here.]); // Getting the length of self.
int length4 = 0; // Because anarchy
if (length1 > length2){ // An if statement to match length4 with the longest array.
length4 = length2;
} else {
length4 = length1;
}
IntArray* newArray; // New IntArray on the heap.
newArray = new* int[length4];
int k = 0;
for (int j = 0; j < length1; j++){ // Two for loops getting the iterator on the same page.
for (int i = 0; i < length2; i++){
if (ary.get(j) == [//The this from earlier, whatever it is][i]){ // Checking to see if digits match each other.
newArray[k] = (ary[j]); // Writing the digit into the NewArray.
k++; // Adding one to the k count to progress the the iterator.
}
}
}
return newArray;
}
bool isSubsequence(int *array) {
int length = getLength(array);
for (int i = 0; i < length - 1; i++) {
if (array[i] != array[i + 1])
return false;
}
return true;
}

Your implementation of findIntersection is not defined as a member function, you have defined it as a global function. The member function declaration named findIntersection is not defined. In short: you forgot IntArray:: before the function name

Related

Reversing an array using pointers

I have this program that makes and populates an array. Then it is sent to a function called reverse, which reverses the order in the array. The compiler keeps giving errors. I'm not quite sure why.
CODE
void reverse(int* array, int size) {
for (int i = 0; i < size/2; i++) {
int temp = array[i];
array[i] = array[size-i];
array[size-i] = temp;
} // end of for loop
} // end of reverse
int main( int argc, char** argv ) {
int array[8];
// get and print size of the array
int size = sizeof(array) / sizeof(array[0]);
printf("Size is %d\n", size);
// populate array
for (int i = 0; i < size; i++) {
array[i] = i;
} // end of for loop
// display array before reversing
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
} // end of for loop
// new line
printf("\n");
// reverse the array
reverse(&array, size);
// display the array again after reversing
for (int i = 0;i < size; i++) {
printf("%d ", array[i]);
} // end of for loop
} // end of main
It keeps giving me this error
main.cc:17:14: error: indirection requires pointer operand ('int' invalid)
int temp = *array[i];
^~~~~~~~~
main.cc:18:3: error: indirection requires pointer operand ('int' invalid)
*array[i] = *array[size-i];
^~~~~~~~~
main.cc:18:15: error: indirection requires pointer operand ('int' invalid)
*array[i] = *array[size-i];
^~~~~~~~~~~~~~
main.cc:19:3: error: indirection requires pointer operand ('int' invalid)
*array[size-i] = temp;
^~~~~~~~~~~~~~
4 errors generated.
make: *** [main.o] Error 1
I did solve this problem a little differently, maybe you will use this code:
#include <iostream>
void displayArray(int table[], int size);
void rev(int table[], int size);
void fillTheArray(int table[], int size);
int main(int argc, char** argv) {
int myArray[8];
int size = sizeof(myArray) / sizeof(myArray[0]);
std::cout << "Array size is: " << size << std::endl;
fillTheArray(myArray, size);
displayArray(myArray, size);
std::cout << std::endl;
rev(myArray, size);
displayArray(myArray, size);
std::cin.get();
return 0;
}
void fillTheArray(int table[], int size) {
for (int i = 0; i < size; i++) {
table[i] = i;
}
}
void displayArray(int table[], int size) {
for (int i = 0; i < size; i++) {
std::cout << table[i] << " ";
}
std::cout << std::endl;
}
void rev(int table[], int size) {
int *start = table;
int *end = table + (size - 1);
for (int i = 0; i < size; i++) {
if (start < end) {
int temp = *end;
*end = *start;
*start = temp;
}
start++;
end--;
}
}
I can see two errors in this code. First is: wrong way of passing parametr to function:
// reverse the array
reverse(&array, size);
you should do this just like this(array name is pointer to first element of this array):
reverse(array, size);
Second problem is with reverser - you try to access some random memory outside arrar range:
array[i] = array[size-i];
Remember that in C++ array index's start with 0 not 1. So if your array is size of 8 - largest insext of this array is 7 (0, 1, 2, 3, 4, 5, 6, 7). Your code should look like this:
array[i] = array[size -i -1];
And it should work as you expected.
It is my solution with pointers:
void reverse(int arr[], int count)
{
int* head = arr;
int* tail = arr + count - 1;
for (int i = 0; i < count/2; ++i)
{
if (head < tail)
{
int tmp = *tail;
*tail = *head;
*head = tmp;
head++; tail--;
}
}
for (int i = 0; i < count; ++i)
{
std::cout << arr[i] << " ";
}
}
or just use functions build in C++: std::reverse in 'algorithm' library.
It's a lot of examples on stackoverflow with this kind of examples:
Reverse Contents in Array
You have fixed most of the compiler errors in your code except one.
The line
reverse(&array, size);
should be
reverse(array, size);
After that is fixed, you have to fix logic errors in reverse.
You are using the wrong index for accessing the upper half of the array.
void reverse(int* array, int size) {
for (int i = 0; i < size/2; i++) {
int temp = array[i];
array[i] = array[size-i]; // When i is 0, you are accessing array[size]
// That is incorrect.
array[size-i] = temp;
} // end of for loop
} // end
You need to use
void reverse(int* array, int size) {
for (int i = 0; i < size/2; i++) {
int temp = array[i];
array[i] = array[size-i-1];
array[size-i-1] = temp;
}
}
Another way to approach the algorithm would be to use two indices.
void reverse(int* array, int size) {
for (int i = 0, j = size-1; i < j; ++i, --j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Working program: http://ideone.com/ReVnGR.
You're passing **int instead of *int to the reverse method:
reverse(&array, size);
Pass it like that:
reverse(array, size);

How do I fix this error? CRT detected that the application wrote to memory after end of heap buffer

I've been trying to make a dynamic array. My main method calls push_back() to add ints to an array 50 times. The push_back() method calls the grow_if_needed() method if the size of the array needs to be doubled. The size() method returns the current capacity of the array. And the toString method is for printing the array as a string. I keep getting this error at the end of the grow_if_needed() method.
#include <string>
class ArrayList
{
private:
static int capacity;
static int count;
public:
int& operator [](int i);
int *arrayPtr = new int[1];
ArrayList();
int * push_back(int m);
int * grow_if_needed();
int * erase(int m);
int size();
std::string toString();
};
#include "ArrayList.h"
using namespace std;
int ArrayList::capacity = 1;
int ArrayList::count = 0;
int & ArrayList::operator[](int i)
{
return arrayPtr[i];
}
ArrayList::ArrayList()
{
arrayPtr[0] = 0;
}
int * ArrayList::push_back(int m)
{
if (count == size()) {
grow_if_needed();
}
for (int i = size() - 1; i >= 0; i--) {
arrayPtr[i + 1] = arrayPtr[i];
}
arrayPtr[0] = m;
count++;
return arrayPtr;
}
int * ArrayList::grow_if_needed() {
int k;
capacity = size() * 2;
int * tempArray = new int[capacity];
for (k = 0; k < count; k++) {
tempArray[k] = arrayPtr[k];
}
while (k != capacity) {
tempArray[k] = 0;
k++;
}
delete [] arrayPtr;
arrayPtr = tempArray;
return arrayPtr;
}
int ArrayList::size()
{
return capacity;
}
string ArrayList::toString()
{
string num = "";
for (int i = 0; i <= size() - 1; i++) {
num += std::to_string(arrayPtr[i]) + " ";
}
return num;
}
In your push_back function you have this loop:
for (int i = size() - 1; i >= 0; i--) {
arrayPtr[i + 1] = arrayPtr[i];
}
Here size() - 1 is the top index, so in the first iteration when you do i + 1 you are out of bounds.
Also, this function is called push_back, but it attempts to add to the front? If it added to the end (the "back") you would not need the loop, and your problem would "magically" disappear.

Shifting array to replace removed element

I am supposed to get the output 8, 6. But I get 8,9 when this code is run. Why am I getting the out put 8,6 and how can I fix the code to make the output become 8,9.
int inputarray[]={9,8,9,9,9,9,6};
int length = 7;
int value = 9;
void arrayShift(int arr[], int length, int value)
{
for(int i = 0; i<length; i++)
{
if(arr[i] == value)
{
for (int k = i; k<length ; k++)
{
arr[k] = arr[k+1];
}
arr[length-1] = 0;
}
}
}
When shifting array, you may replace first element (containing number equal to value) with the same value from other element. In that case, you need to restart iteration on this element again, e.g.:
void arrayShift(int arr[], int length, int value)
{
for(int i = 0; i<length; i++)
{
if(arr[i] == value)
{
for (int k = i; k<length-1 ; k++)
{
arr[k] = arr[k+1];
}
arr[length-1] = 0;
i--; // <-- this
}
}
}
Your algorithm for shifting is wrong: you fail to adjust i on removal. In addition, it is rather inefficient: you can do this in a single loop with two indexes - r for reading and w for writing. When you see the value you want to keep, adjust both the reading and the writing index. Otherwise, increment only the reading index.
Once the reading index reaches the count, the writing index indicates how many items you have left. You need to return it to the caller somehow, otherwise he wouldn't know where the actual data ends. You can return the new length as the return value of your function, or take length as a pointer, and adjust it in place.
int arrayShift(int arr[], int length, int value) {
int r = 0, w = 0;
for (; r != length ; r++) {
if (arr[r] != value) {
arr[w++] = arr[r];
}
}
return w;
}
Here is how you call it:
int inputarray[]={9,8,9,9,9,9,6};
int length = 7;
int value = 9;
int newLen = arrayShift(inputarray, length, value);
for (int i = 0 ; i != newLen ; i++) {
printf("%d ", inputarray[i]);
}
printf("\n");
Demo.

how to shift elements of array (or c-string) left by a given number indexes

I am writing a function to shift the characters of my c-string left by a given number of characters. Currently the function will shift the characters left but I am losing one. I know it is some sort of indexing issue with my for loop, but I can't pin it down.
EDIT: By shift left I mean:
Given a starting c-string of a, b, c, d
if shifted left one index this same array would equal b, c, d, a
if shifted left two indexes this same c-string would equal c, d, a, b
Here is my code so far:
#include <iostream>
using namespace std;
void shiftleft (char myarray[], int size, int shiftBy)
{
char temp;
for (int i=size-1; i > 0; i--)
{
temp = myarray[size+shiftBy];
myarray[size+shiftBy] = myarray[i];
myarray[i] = temp;
}
}
int main() {
char myarray[20] = "test";
int size = 4;
shiftleft (myarray, size, 1);
for(int i = 0; i < size+1; i++){
cout << myarray[i];
}
return 0;
}
Here is my working function that shifts each element to the right, all I need to do is reverse this loop, and move the elements left, as in this way: <----
//function bloack
void shiftright (char myarray[], int size, int shiftBy)
{
if(shiftBy > size){
shiftBy = shiftBy - size;
}
if(size == 1){
//do nothing
}
else{
char temp;
//for loop to print the array with indexes moved up (to the right) --> by 2
for (int i=0; i < size; i++)
{
temp = myarray[size-shiftBy];
myarray[size-shiftBy] = myarray[i];
myarray[i] = temp;
}
}
}
if you want shift string to left and don't rotate, you can use this code:
void shiftLeft (char *string,int shiftLength)
{
int i,size=strlen(string);
if(shiftLength >= size){
memset(string,'\0',size);
return;
}
for (i=0; i < size-shiftLength; i++){
string[i] = string[i + shiftLength];
string[i + shiftLength] = '\0';
}
}
With a little fanangling, I was able to get it to work. Here is my functioning function :)
The issue was that I needed to assign element i to i+shiftBy, and only repeat the loop while i < size-shiftBy.
//function bloack
void shiftLeft (char myarray[], int size, int shiftBy)
{
if(shiftBy > size){
shiftBy = shiftBy - size;
}
if(size == 1){
//do nothing
}
else{
char temp;
//for loop to print the array with indexes moved up (to the left) <-- by 2
for (int i=0; i < size-shiftBy; i++)
{//EXAMPLE shift by 3 for a c-string of 5
temp = myarray[i];//temp = myarray[0]
myarray[i] = myarray[i + shiftBy];//myarray[0] == myarray[2]
myarray[i + shiftBy] = temp;//myarray[2] = temp(value previously at index i)
}
}
}
// Suppose if j is your len of shift
char* name = strdup("Hello");
char* str_ptr = (char*) malloc(sizeof(char));
strcpy(str_ptr, name);
int j = 3 // len of shift
for(int i = 0; i < strlen(str_ptr); i++){
printf("%c", str_ptr[(i+j)%strlen(str_ptr)]);
}

How to initialize a class Object of Typename T?

For a C++ class I am taking, I am creating a Vector Library. We are not allowed to use the built in vector library, of course, and I have decided to use arrays in my 'myvector' class.
I am currently trying to test my code and I am not sure how to create an object of class myvector.
The error I get is Incomplete type is not allowed.
main.cpp:
#include "my_vectorHeader.h"
using namespace std;
int main(){
myvector<int> vector = new myvector<int>(3);
}
my_vectorLib.cpp:
#include "my_vectorHeader.h"
#include iostream
#include exception
using namespace std;
template<typename T> class myvector {
private:
int vector_size, //holds current size
vector_capacity; //holds current capacity
public:
//constructors
myvector<T>(int length){
T vector[length];
vector_size = length;
vector_capacity = length;
}
myvector<T>(const T& doppelganger){
T vector = doppelganger;
while(vector[vector_size] != NULL)
vector_size++;
}
myvector<T>(const T& dat_arr, int arr_size){
vector_size = arr_size;
vector_capacity = arr_size;
for(int i = 0; i < arr_size; i++)
vector[i] = dat_arr[i];
}
~myvector(){ //destructor
delete [] vector;
delete myvector;
}
myvector& myvector::operator[](int index){ //override []
try{
throw vector[index];
} catch(exception e){
cout << e.what() << endl;
}
return vector[index];
}
T at(int index){
return vector[index];
}
int size(){
return vector_size;
}
int capacity(){
return vector_capacity;
}
bool empty(){
if(size() > 0)
return false;
else
return true;
}
void resize(int new_size){
T vector_copy[new_size];
for(int i = 0; i < new_size; i++){
if(i >= vector_size)
vector_copy[i] = NULL;
else
vector_copy[i] = vector[i];
if(new_size > capacity)
capacity = new_size;
}
vector_size = new_size;
delete [] vector;
T *vector;
vector = vector_copy;
for(int i = 0; i < vector_size; i++)
vector[i] = vector_copy[i];
delete [] vector_copy;
}
void reserve(int new_capacity){
if(new_capacity < vector_size){
cout << "Error. Newly provided vector capacity is smaller than the current vector size. The capacity is " << vector_capacity << " and has not been changed.";
} else {
vector_capacity = new_capacity;
}
}
T pop_back(){
T return_val = vector[size() - 1];
resize(size() - 1);
return return_val;
}
void push_back(T new_val){
resize(size() + 1);
vector[size() - 1] = new_val;
}
void assign(int position, T new_val){
vector[position] = new_val;
}
void clear(){
for(int i = 0; i < size(); i++)
vector[i] = NULL;
}
void erase(int position){
vector[position] = NULL;
do{
vector[position] = vector[position + 1];
}while(position != NULL);
resize(size() - 1);
}
void erase(int in, int between){
int i = in + 1, j = between;
while(i < between){
vector[i] = vector[j];
vector[j] = NULL;
i++, j++;
}
resize(between);
}
void insert(int index, T new_val){
for(int i = size + 1; i > index; i--)
vector[i] = vector[i - 1];
vector[index] = new_val;
}
};
Declaration and implementation of templates should be in the same file(or implementation should be included too). Also this
myvector<int> vector = new myvector<int>(3);
is incorrect(new returns pointer) and unnecessary. Just use
myvector<int> vector(3);
Put the class (all the code) found at my_vectorLib.cpp in your my_vectorLib.h As #soon pointed you, templates classes (unless specialized) need to be at the header file (the one you include at main.cpp which where the class is instantiated, which means the compiler generates the actual code when you use the template).