I am trying to get this function to create anew array to be 2x the size of the array argument, copy the contents into the new array, and for the second half of the array, create new values by doing 2*the values in the first half of the array, then delete the original array. Repeat this process for the specified number of times, then return the new array. I feel like I have the right algorithm down but my code isn't working. Please help!
int *ArrayDynamicAllocation(int array[], int size, int number)
{
int *new_array = NULL;
for(int i=0; i<number-1; i++)
{
new_array = new int[size*2];
for(int j=0; j<size-1; j++)
{
new_array[j]=array[j];
new_array[j+size]=2*array[j];
}
array=new_array;
delete[] array;
size=size*2;
}
return new_array;
}
An example output would be if my info to put into my function was
int arr[2] = {0,1};
array_size = 2;
number = 3;
I want it to output 0 1 0 2 0 2 0 4 0 2 0 4 0 4 0 8
int *ArrayDynamicAllocation(int array[], int size, int number)
{
int *new_array = NULL;
int *tmp_array = new int[array.length()];
for(int k=0; k<array.length(); k++)//Initial array copying.
tmp_array[k] = array[k];
for(int i=0; i<number; i++)//Array range 0 to n-1
{
new_array = new int[size*2];
for(int j=0; j<size; j++)//Array range 0 to n-1
{
new_array[j]=tmp_array[j];
new_array[j+size]=2*tmp_array[j];
}
delete[] tmp_array //Deleting old array
size=size*2;
tmp_array = new int[size] //Allocating memory for next iteration
for(int k=0; k<size; k++)
tmp_array[k] = new_array[k];//Copying array for next iteration
}
delete[] tmp_array;// To free memory
return new_array;
};
c array range from 0 to size-1
change
for(int i=0; i<number-1; i++)
to
for(int i=0; i<=number-1; i++)
change
for(int j=0; j<size-1; j++)
to
for(int j=0; j<=size-1; j++)
you are deleting wrong array
change
array=new_array;
delete[] array;
to
delete[] array;
array=new_array;
template<class T>
void changeSize1d(T*&a, const int oldSize, const int newSize){
if(newSize<0)return 0;
T*temp new T[newSize];
int number = min(oldSize, newSize);
copy(a, a+number, temp);
delete [] a;
a = temp;
}
Related
I'm working with c++ arrays and I found a problem. I can easily do the exercise using cin and filling array with for loop. But when I try to do it as filled array I got the error with too many initializer values. How to solve it?
#include <iostream>
using namespace std;
void func(int **arr, int row, int col)
{
for (int i=0; i<row; i++)
{
for(int j=0 ; j<col; j++)
{
cout<<arr[i][j]<<" ";
}
printf("\n");
}
}
int main()
{
int row = 2;
int colum = 2;
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
arr[i] = new int[colum];
}
arr = {
{1,2},
{3,4}};
func(arr, row, colum);
return 0;
}
arr is a pointer
int** arr = new int*[row];
So it may be initialized with a braced list containing only one (assignment) expression.
For the allocated array of two elements you could write for example
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
if ( i == 0 ) arr[i] = new int[colum] { 1, 2 };
else arr[i] = new int[colum] { 3, 4 };
}
or
int** arr = new int*[row];
for(int i=0, value = 1; i<row; i++)
{
arr[i] = new int[colum] { value++, value++ };
}
Pay attention to that you will need to free the dynamically allocated memory for the arrays.
Otherwise use the standard container std::vector<std::vector<int>> instead of the allocated dynamically arrays.
I need to insert a value into my array without using vector library. The way inserted it is by replacing the number at the index into which i wanna insert the number. I need to insert a number to an arbitrary index and move everything after the index to the right by keeping all the values. I tried doing it by creating a new array, but unfortunately no good..
void Vector::insert(int value, int index)
{
//initializing array to copy from index
int* new_arr = new int[current];
//copying everything from given index to the end
for(int i = 0; i < current; i++){
if((arr[index+1]) != NULL){
new_arr[i] = arr[index + i];
}
}
//replaces the given value at the given index
arr[index] = value;
//copying before and after the index into one array
int* total_arr = new int[current+1];
//before index
for (int i = 0; i < index; i++){
total_arr[i] = arr[i];
}
//after index
for(int i = index; i< current+1; i++){
total_arr[i] = new_arr[i];
}
capacity += 1;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
arr[i] = total_arr[i];
}
//replaces the given value at the given index
arr[index] = value;
//copying before and after the index into one array
int* total_arr = new int[current+1];
//before index
for (int i = 0; i < index; i++){
total_arr[i] = arr[i];
}
//after index
for(int i = index; i< current+1; i++){
total_arr[i] = new_arr[i];
}
for(int i = 0; i<current+1; i++){
std::cout<<total_arr[i]<<std::endl;
}
for(int i = 0; i<capacity+1; i++){
std::cout<<total_arr[i]<<std::endl;
}
capacity += 1;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
arr[i] = total_arr[i];
}
}
Your code looks too long and complicated.
Not knowing the specification of your class, the implemention should be something like this (assuming arr is the pointer to the data array and current is the number of elements in the array):
void Vector::insert(int value, int index)
{
int* new_arr = new int[current+1];
// positions of elements before insertion won't change
for (int i = 0; i < index; i++) new_arr[i] = arr[i];
// the element to insert
new_arr[index] = value;
// positions of elements after insertion will move by one
for (i = index; i < current; i++) new_arr[i + 1] = arr[i];
// change the arrays
int* old_arr = arr;
arr = new_arr;
delete[] old_arr;
current++;
}
I was learning count sort from tutorial and my C++ source code is given below:
#include <iostream>
#include <string.h>
using namespace std;
void countSort(int arr[], int size)
{
//declare output array
int output[size];
//declare count array
int count[size];
//initialize count[] with zero
//memset ( void * ptr, int value, size_t num )
memset(count, 0, sizeof(count));
//input array element is the index of count array
//storing the repetition/frequency
for(int i=0; i<size; i++){
count[arr[i]]++;
}
/*
Modify the count array such that each element at
each index stores the sum of previous counts.
*/
// i=1 because, previous is 0 due to avoid -1
for(int i=1; i<size; i++){
count[i] += count[i-1];
}
//Build ouput array
//count array element is the index of output array
for(int i=0; i<size; i++){
//***********THIS LINE***********
output[count[arr[i]]-1] = arr[i];
count[arr[i]]--;
}
//copy ouput array into input array arr[]
for(int i=0; i<size; i++){
arr[i] = output[i];
}
}
void printArray(int arr[], int size){
// Ascending order
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
// your code goes here
int arr[] = {1,4,1,2,7,5,2,6,6,9};
int size= sizeof(arr)/sizeof(arr[0]);
countSort(arr, size);
printArray(arr, size);
return 0;
}
I understand about taking sorted array in output array.However why we need to decrements the output index by -1:
output[count[arr[i]]-1] = arr[i];
I didn't understand this part. I try with only output[count[arr[i]]] but it doesn't gave me the correct sorted array.
The array of counts was converted in to an array of ending indices, point one past the end of each logical bucket, so 1 is subtracted from each index. This could be combined to use pre-decrement, and the array scanned backwards:
for(i=size; i; ){
i--;
output[--count[arr[i]]] = arr[i];
}
Getting back to the counts after they are summed up, note that count[0] contains a count of all the elements equal to zero, and count[1] contains a count of all elements == zero and all elements == 1, and so on, so count[0] is the logical size of the bucket that will contain the zeroes, and the size is 1 greater than the index to the last element. The same logic applies to count[1] and so on.
Example code where the counts are converted into starting indices. output[] converted to use new (to avoid stack overflow and some compilers don't support variable length arrays). count[10] assumes the range of numbers is limited to 0 through 9.
#include <iostream>
#include <stdlib.h>
using namespace std;
void countSort(int arr[], int size)
{
//declare output array
int * output = new int[size];
//declare count array
// assumes range of values is 0 to 9
int count[10];
//initialize count[] with zero
for(int i=0; i<size; i++)
count[i] = 0;
//input array element is the index of count array
//storing the repetition/frequency
for(int i=0; i<size; i++){
count[arr[i]]++;
}
// convert counts into starting indices (this is the main change)
int sum = 0, tmp;
for(int i=0; i<size; i++){
tmp = count[i];
count[i] = sum;
sum += tmp;
}
//Build ouput array
//count array element is the index of output array
for(int i=0; i<size; i++){
output[count[arr[i]]++] = arr[i];
}
//copy ouput array into input array arr[]
for(int i=0; i<size; i++){
arr[i] = output[i];
}
delete[] output;
}
void printArray(int arr[], int size){
// Ascending order
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
int arr[] = {1,4,1,2,7,5,2,6,6,9};
int size= sizeof(arr)/sizeof(arr[0]);
countSort(arr, size);
printArray(arr, size);
return 0;
}
It's been a while since I last visited arrays (I've been working with vectors recently) and I need to convert an 2D vector back into a 2D array because of a library I am using accepts the paramaters of type double array where the accessors of this array is foo[i][j] for example.
Here is my code:
double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
double** temp;
temp = new double[N][M];
for(unsigned i=0; (i < N); i++)
{
for(unsigned j=0; (j < M); j++)
{
temp[i][j] = vals[i][j];
}
}
}
And with this, I get error: ‘M’ cannot appear in a constant-expression
I have also tried the following:
double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
double** temp;
for(unsigned i=0; (i < N); i++)
{
temp[i] = new double[N];
for(unsigned j=0; (j < M); j++)
{
temp[j] = new double[M];
temp[i][j] = vals[i][j];
}
}
}
However, this produces a segmentation fault 11.
Could anyone suggest any advice, or, a better way to convert a vector to a 2D array..
Thanks
You were close. It should be:
double** setupHMM(vector<vector<double> > &vals, int N, int M)
{
double** temp;
temp = new double*[N];
for(unsigned i=0; (i < N); i++)
{
temp[i] = new double[M];
for(unsigned j=0; (j < M); j++)
{
temp[i][j] = vals[i][j];
}
}
}
A double pointer (double**) is not convertible to a 2D array.
double** temp;
temp = new double[N][M]; //invalid
double** temp;
temp = new double(*)[M];
It's a common misunderstanding to think that because an 1D array decays to a pointer that therefore a 2D array will decay to a double pointer. This is not true. The decay only happens with a single pointer.
replace
temp[i] = new double[N];
with
temp = new double*[N];
in the second code, and move it outside the loop
after reading inputs to an array:
int * inputs;
the "inputs" is 1 dimensional array: inputs[6], then reading this array out, the values are:
inputs[0]=1
inputs[1]=2
inputs[2]=3
inputs[3]=4
inputs[4]=5
inputs[5]=6
I would like to read this array into another one dimensional array:
int counter=0;
int * allElements = new int[6];
for(int i=0; i<6; i++)
{
allElements[counter++] = inputs[i];
}
That is a traditional way of reading all of the elements into one dimensional array and I believe if I read the elements of "allElements" this way:
for(int i=0; i<6; i++)
printf("%d ", allElements[i]);
and it should be: 1 2 3 4 5 6
However, I would like to read all elements of that array into the 1 dimensional array such that when I do it like this:
for(int i=0; i<6; i++)
printf("%d ", allElements[i]);
It should be: 1 3 5 2 4 6
How can I achieve this way?
int * allElements = new int[6];
for(int i=0; i<6; i+=2)
{
allElements[i/2] = inputs[i];
allElements[3+i/2] = inputs[i+1];
}
What about:
for(int i=0; i<6; i++)
{
allElements[i] = inputs[2*(i%3) + (i/3)];
}
Imagine inputs is a two-dimension array, of 3x2, then i%3 is one coordinate and i/3 the other. Just transpose it into a 2x3 matrix, and done!
const int size =6;
int inputs[size]={1,2,3,4,5,6};
int allElements[size];
...
if (size % 2)
{
int middle=(size/2) +1;
for(int i=0; i<size; i+=2)
{
allElements[i/2] = inputs[i];
if (i < size-2)
allElements[middle+i/2] = inputs[i+1];
}
}
else
{
int middle=size/2;
for(int i=0; i<size; i+=2)
{
allElements[i/2] = inputs[i];
allElements[middle+i/2] = inputs[i+1];
}
}
Logic can definitely be simplified. Just first attempt and left it alone.
If want it to work for the 1 case
allElements[0]=inputs[0];
allElements[1]=inputs[2];
allElements[2]=inputs[4];
allElements[3]=inputs[1];
allElements[4]=inputs[3];
allElements[5]=inputs[5];