for one of my assignments I have to create a class that creates a dynamic array and has methods to add or remove a number from the array, I figured out how to do the add method and it works fine but I cannot figure out how to remove an element and make the size of the array decrease by one.
#include <iostream>
using namespace std;
class IntegerDynamicArray
{
public:
IntegerDynamicArray()
{
currentSize = 0;
maxSize = 10;
dynamicArray = new int[maxSize];
}
int add(int x);
bool remove(int x);
private:
int* dynamicArray;
int currentSize;
int maxSize;
};
int IntegerDynamicArray::add(int x)
{
if (currentSize == maxSize)
{
maxSize = maxSize * 2;
int* tempArray = new int[maxSize];
for (int i = 0; i < currentSize; i++)
{
tempArray[i] = dynamicArray[i];
}
tempArray[currentSize] = x;
currentSize++;
dynamicArray = tempArray;
}
else
{
dynamicArray[currentSize] = x;
currentSize++;
}
return currentSize;
}
bool IntegerDynamicArray::remove(int x)
{
for (int i = 0; i < currentSize; i++)
{
if (dynamicArray[i] == x)
{
//TODO need to delete the number and move all numbers "back" by one
return true;
}
}
return false;
}
int main()
{
IntegerDynamicArray intDynArray;
while (1)
{
char input;
cout << "Enter A for add or R for remove: ";
cin >> input;
if (input == 'A')
{
cout << "Enter number to add: ";
int x;
cin >> x;
cout << intDynArray.add(x) << endl;
}
else if (input == 'R')
{
cout << "Enter number to remove: ";
int x;
cin >> x;
cout << intDynArray.remove(x) << endl;
}
}
}
The add function leaks memory because you did not deallocate dynamicArray before assigning it to the new block of memory. You should also provide a destructor. Use delete[] rather than delete since you are allocating an array. The conditional within remove does not appear to be correct. I would think that x indicates the element to remove, but you are searching for an element with value == x. I would think that you would first validate that x is a valid index (less than current size), and then use x to loop from that element to the end copying all of the elements forward. Then zero initialize between currentSize and max size. That would be one way to do it. This look like homework, so I will only provide guidance and not the code. Try it. Based on what you wrote so far, I think that you can figure that out.
Update: It is true that if you add a destructor that handling copy construction and assignment (somehow) is critical.
If you really want to remove occurrences of a value rather than the element, then I suggest you do it similarly to how the remove algorithm does it. Essentially you would start at the beginning, loop and copy forward over the matched values. Since you aren't dealing with iterators you'd have to get creative and adjust your current size but the example there on cplusplus.com should be invaluable in helping you write your function. Although technically you don't have to zero initialize those "removed" slots, I think that it is a good idea so that you don't get confused while debugging. Stale data in those unused slots doesn't help but it could get confusing while looking at the data in a debugger.
This ought to do it:
bool IntegerDynamicArray::remove(int x)
{
for (int i = 0; i < currentSize; i++)
{
if (dynamicArray[i] == x)
{
int *newArray = new int[currentSize-1];
std::copy(dynamicArray, dynamicArray+i, newArray);
std::copy(dynamicArray+i+1, dynamicArray+currentSize, newArray+i);
delete[] dynamicArray;
dynamicArray = newArray;
--currentSize;
return true;
}
}
return false;
}
If you want to remove the first occurrence only you can do something like that. I didn't test the code but it should be fine.
bool IntegerDynamicArray::remove(int x)
{
for (int i = 0; i < currentSize; i++)
{
if (dynamicArray[i] == x)
{
for ( ; i < currentSize - 1; i++)
{
// Assign the next element to current location.
dynamicArray[i] = dynamicArray[i + 1];
}
// Remove the last element as it has been moved to previous index.
dynamicArray[currentSize - 1] = 0;
currentSize = currentSize - 1;
return true;
}
}
return false;
}
You can also write a function that removes all occurrences of the value or as #shawn1874 suggested you can remove the item with the given index.
Related
Write a function, equalsArray that when passed two int arrays of the same length that is greater than 0 will return true if every number in the first array is equal to the number at the same index in the second array. If the length of the arrays is less than 1 the function must return false. For example, comparing the two arrays, {1,2,3,4,5} and {1,2,3,4,5} would return true but the two arrays {3,7} and {3,6} would return false.
You should start by copying the function-1-1.cpp file and name it function-3-1.cpp. Then add the function equalsArray to the new file.
The main function for this problem must call your readNumbers function twice, then pass both new arrays to your equalsArray function, display the result as true or false and finally delete the array. The main function in the file main-3-1.cpp.
The signature for your new function is:
bool equalsArray(int *numbers1,int *numbers2,int length) ;
This is my code, and i try to use the int* readNumber two times.
#include <iostream>
using namespace std;
int* readNumbers()
{
int* a = new int[10];
for (int i = 1; i < 11; i++) {
int x;
cin >> x;
a[i] = x;
}
a++;
return a;
// delete[] a;
}
bool equalsArray(int* numbers1, int* numbers2, int length)
{
if (length >= 1) {
for (int i = 0; i < length; i++) {
if (numbers1[i] == numbers2[i]) {
}
else {
return false;
}
}
return true;
}
// delete[] numbers1;
// delete[] numbers2;
int main()
{
int* arr1 = readNumbers();
int* arr2 = readNumbers();
equalsArray(arr1, arr2, 10);
return 0;
}
There there is an error,control reaches end of non-void function.
How to improve my code?
Thank you all.
Expect result:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
True(1)
OK, first I will show you your code, with comments where the errors are.
Then I will show you a fixed version. And, at the end, a little bit more robust C++ soultion.
I know that you learn in school all this nasty stuff with pointers, decayed pointers for arrays, C-style arrays,pointers for owned memory, new and delete.
That is basically bad. It should never be used in C++.
Anyway. Teachers still think like that. What a pity . . .
OK. You code with comments:
#include <iostream>
using namespace std; // Should not be used
int* readNumbers()
{
int* a = new int[10]; // Do not use C-style arrays, pointer for owned memory, new and delete
for (int i = 1; i < 11; i++) { // Will lead to out of bound error
int x; // Why using additional variables?
cin >> x;
a[i] = x;
}
a++; // Wrong
return a;
// delete[] a; // Not here
}
bool equalsArray(int* numbers1, int* numbers2, int length)
{
if (length >= 1) {
for (int i = 0; i < length; i++) {
if (numbers1[i] == numbers2[i]) {
}
else {
return false;
}
}
return true;
}
// Here nothing will be returned
} // Closing bracket misding
// delete[] numbers1; // Not here
// delete[] numbers2; // Not here
int main()
{
int* arr1 = readNumbers();
int* arr2 = readNumbers();
equalsArray(arr1, arr2, 10);
return 0; // No output
} // No Release of memory
Next, your fixed code
#include <iostream>
using namespace std;
// Function to read a given numbers of values and returns them in a dynaimcally allocated array
int* readArrayOfNumbers(int numberOfValuesToRead) {
// Allocate a new array for the given amount of integers
int* dynamicArrayOfIntegers = new int[numberOfValuesToRead];
// Read all values in a loop from user via std::cin
for (int index = 0; index < numberOfValuesToRead; ++index) {
cin >> dynamicArrayOfIntegers[index];
}
return dynamicArrayOfIntegers;
}
// Compare 2 arrays with same size
bool equalsArray(int* numbers1, int* numbers2, int length) {
// We assume in the beginning that the arrays will be equal
bool result = true;
// We will only compare arrays, if they contain data
if (length >= 1) {
// Now compare arrays element by element
for (int i = 0; i < length; i++) {
if (numbers1[i] != numbers2[i]) {
// If not equal then set result to false and stop loop
result = false;
break;
}
}
}
else {
// No data in array. Consider as not equal
result = false;
}
return result;
}
int main()
{
// Define size of arrays
const int sizeOfArray = 10;
// Get 2 arrays in dynamically allocated arrays
int* array1 = readArrayOfNumbers(sizeOfArray);
int* array2 = readArrayOfNumbers(sizeOfArray);
// Compare both arrays
const bool arraysAreEqual = equalsArray(array1, array2, sizeOfArray);
// Show result
if (arraysAreEqual)
std::cout << "\nTrue(1)\n";
else
std::cout << "\nFalse(0)\n";
// Release memory
delete[] array1;
delete[] array2;
}
And finally, the C++ solution
#include <iostream>
#include <iomanip>
#include <array>
constexpr size_t NumberOfElements = 10u;
using MyType = int;
using MyArray = std::array<MyType, NumberOfElements>;
int main() {
// Define arrays
MyArray myArray1{};
MyArray myArray2{};
// Read values
for (size_t i{}; (i < NumberOfElements) and (std::cin >> myArray1[i]); ++i)
;
for (size_t i{}; (i < NumberOfElements) and (std::cin >> myArray2[i]); ++i)
;
// If all numbers could be read . . .
if (std::cin) {
// Show result of comparison
std::cout << '\n' << std::boolalpha << (myArray1 == myArray2) << '(' << (myArray1 == myArray2) * 1 << ")\n";
}
else std::cerr << "\n*** Error. Invalid input data\n";
}
On the input we get a sentence which we read until EOF. We need to add single words to dynamic array and then write them one on each line.
Input: Hello this, is an example.
Output:
Hello
this,
is
an
example
I have the following code and I can't figure out why it doesn't even add anything to the array.
#include <iostream>
#include <string>
using namespace std;
void addToArray(string newWord, string myArray[], int& arrayLength)
{
string * tempArray = new string[arrayLength + 1];
tempArray[arrayLength] = newWord;
for (int i = 0; i < arrayLength; ++i)
{
myArray[i] = tempArray[i];
}
arrayLength++;
myArray = tempArray;
delete [] tempArray;
}
int main()
{
string * arrayOfWOrds = new string[1000];
int arrayLength = 0;
string temp;
while (getline(cin, temp))
{
cout << temp << endl;
addToArray(temp, arrayOfWOrds, arrayLength);
}
cout << "Array" << endl;
for (int i = 0; i < arrayLength; ++i)
{
cout << arrayOfWOrds[i] << endl;
}
}
It's because you don't return the new array from the addToArray function. The change you make only happens in addToArray, it doesn't happen in main.
You also delete[] the wrong array, you delete the array you've just created.
You also copy the array elements in the wrong direction, i.e. from your new array to your old array.
Try this, I've renamed some of the variables for clarity. There is no temporary array in your function only a new array and an old array. Choosing good variable names is very important for writing working code. Bad variable names just confuse yourself.
string* addToArray(string newWord, string* oldArray, int& arrayLength)
{
string * newArray = new string[arrayLength + 1];
newArray[arrayLength] = newWord;
for (int i = 0; i < arrayLength; ++i)
{
newArray[i] = oldArray[i];
}
arrayLength++;
delete [] oldArray;
return newArray;
}
Then use it like this
arrayOfWOrds = addToArray(temp, arrayOfWOrds, arrayLength);
I see several issues here. To begin with, you set arrayLength = 0, so it's not going to iterate over the whole array if you have stuff already in it. If you don't have anything in it, there's no point in making it start off with 1000 items. Also, while (getline(cin,temp)) is an infinite loop, so it will never end and actually print the array. If you want to print the array after each addition, you need to move it into the while loop. There's no real reason to cout the number the user types either; they can already see the line they just typed.
More importantly, there are real issues with the dynamic allocation. You've created a static array (string * arrayOfWOrds = new string[1000];), then you're giving that to the function which makes a new array one item larger, sets the last item in that array to the new value, then iterates over the entire new array and duplicates the values to the old array. Basically, you're just inserting items into the static array at that point, and what you're inserting is a bunch of nothing (because the new array only has one item in it, and it's at arrayLength+1 which is outside the bounds of the original array).
You need to delete the old array, not the new array, which actually should be thrown on the heap and returned.
Basically, it should look more like this:
#include <iostream>
#include <string>
using namespace std;
string* addToArray(string newWord, string myArray[], int& arrayLength)
{
string * returnArray = new string[arrayLength + 1];
returnArray[arrayLength] = newWord;
for (int i = 0; i < arrayLength; ++i)
{
returnArray[i] = myArray[i];
}
arrayLength++;
delete [] myArray;
return returnArray;
}
int main()
{
const int startSize = 0;
string * arrayOfWords = new string[1];
int arrayLength = startSize;
string temp;
cout << "Input: ";
getline(cin, temp);
string word = "";
for (char c : temp){
if (c == ' '){
arrayOfWords = addToArray(word, arrayOfWords, arrayLength);
word = "";
} else word.push_back(c);
}
arrayOfWords = addToArray(word, arrayOfWords, arrayLength); // Don't forget the last word
for (int i = 0; i < arrayLength; ++i)
{
cout << arrayOfWords[i] << endl;
}
}
The array is unchanged, because you pass the pointer to the addToArray function, but it has no way to pass the new pointer back. You can fix this by changing the signature of the function to
void addToArray(string newWord, string *myArray[], int& arrayLength)
You also need to change the code accordingly, and fix problem with deallocation.
You can save yourself all the trouble and use std::vector in place of manually allocated dynamic array:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> arrayOfWOrds;
string temp;
while (getline(cin, temp))
{
cout << temp << endl;
arrayOfWOrds.push_back(temp);
}
cout << "Array" << endl;
for (size_t i = 0; i < arrayOfWOrds.size(); ++i)
{
cout << arrayOfWOrds[i] << endl;
}
}
string in="dasd adas ads adsada adsa asd ads",out;
stringstream ss(in);
vector<string> vr;
while(ss>>out)
{
vr.push_back(out);
//cout<<out<<endl;
}
for(int i=0;i<vr.length();i++)
{
cout<<vr[i]<<endl;
}
try doing this
The code below – it's a skeleton of a program operating on the dynamic collection of data. The idea is to use a structure containing two fields: the first stores the number of elements in collections, and the second is the actual collection (a dynamically allocated vector of ints). As you can see, the collection is filled with the required amount of pseudo-random data.
Unfortunately, the program requires completion, as the most important function.
Here's what i expect from the function:
if the collection is empty, it should allocate a one-element vector and store a new value in it.
if the collection is not empty, it should allocate a new vector with a length greater by one than the current vector, then copy all elements from the old vector to the new one, append a new value to the new vector and finally free up the old vector.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Collection {
int elno;
int *elements;
};
void AddToCollection(Collection &col, int element) {
//the first part of the funtion
if (col.elno==0){
col.elements= new int[1];
col.elements[0]= element;
}
//this is the second part but i do not know how to do it.
//Please help me to complete***************
else {
int *temp;
temp = new[];
}
}
void PrintCollection(Collection col) {
cout << "[ ";
for(int i = 0; i < col.elno; i++)
cout << col.elements[i] << " ";
cout << "]" << endl;
}
int main(void) {
Collection collection = { 0, NULL };
int elems;
cout << "How many elements? ";
cin >> elems;
srand(time(NULL));
for(int i = 0; i < elems; i++)
AddToCollection(collection, rand() % 100 + 1);
PrintCollection(collection);
delete[] collection.elements;
return 0;
}
vector container is originally dynamic container. so u can use vector.
Just declare vector variable in structure and use it in AddToCollection function.
struct Collection {
int elno;
std::vector<int> elements;
};
void AddToCollection(Collection &col, int element) {
col.elements.push_back(element);
col.elno++;
}
like this.
Here is what you are looking for:
void AddToCollection(Collection &col, int element)
{
if(col.elements == NULL)
{
col.elements = new int[1];
col.elements[0] = element;
col.elno = 1;
}
else
{
int *newArr = new int[col.elno+1];
for(int i = 0; i < col.elno; i++)
{
newArr[i] = col.elements[i];
}
newArr[col.elno] = element;
delete[] col.elements;
col.elements = new int[col.elno+1];
for(int i = 0; i < col.elno+1; i++)
{
col.elements[i] = newArr[i];
}
delete[] newArr;
newArr = NULL; // avoid dangling pointer
col.elno++;
}
}
For sure using vector container is a great ideea but the exercise require no modification to the main function. The objective of this exercise is to help the student to understand dynamically allocated memory.
I am making a program to identify whether a 5 card ( user input ) array is a certain hand value. Pair, two pair, three of a kind, straight, full house, four of a kind ( all card values are ranked 2-9, no face cards, no suit ). I am trying to do this without sorting the array. I am currently using this to look through the array and identify if two elements are equal to each other
bool pair(const int array[])
{
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
}
Does this section of code only evaluate whether the first two elements are the same, or will it return true if any two elements are the same? I.E if the hand entered were 2,3,2,4,5 would this return false, where 2,2,3,4,5 would return true? If so, how do I see if any two elements are equal, regardless of order, without sorting the array?
edit: please forgive the typos, I'm leaving the original post intact, so as not to create confusion.
I was not trying to compile the code, for the record.
It will do neither:
i < array will not work, array is an array not an int. You need something like int arraySize as a second argument to the function.
Even if you fix that then this; array[i]==aray[i+1] will cause undefined behaviour because you will access 1 past the end of the array. Use the for loop condition i < arraySize - 1.
If you fix both of those things then what you are checking is if 2 consecutive cards are equal which will only work if the array is sorted.
If you really cant sort the array (which would be so easy with std::sort) then you can do this:
const int NumCards = 9; // If this is a constant, this definition should occur somewhere.
bool hasPair(const int array[], const int arraySize) {
int possibleCards[NumCards] = {0}; // Initialize an array to represent the cards. Set
// the array elements to 0.
// Iterate over all of the cards in your hand.
for (int i = 0; i < arraySize; i++) {
int myCurrentCard = array[i]; // Get the current card number.
// Increment it in the array.
possibleCards[myCurrentCard] = possibleCards[myCurrentCard] + 1;
// Or the equivalent to the above in a single line.
possibleCards[array[i]]++; // Increment the card so that you
// count how many of each card is in your hand.
}
for (int i = 0; i < NumCards; ++i) {
// If you want to check for a pair or above.
if (possibleCards[i] >= 2) { return true; }
// If you want to check for exactly a pair.
if (possibleCards[i] == 2) { return true; }
}
return false;
}
This algorithm is actually called the Bucket Sort and is really still sorting the array, its just not doing it in place.
do you know the meaning of return keyword? return means reaching the end of function, so in your code if two adjacent values are equal it immediately exits the function; if you want to continue checking for other equality possibilities then don't use return but you can store indexes of equal values in an array
#include <iostream>
using namespace std;
int* CheckForPairs(int[], int, int&);
int main()
{
int array[ ]= {2, 5, 5, 7, 7};
int nPairsFound = 0;
int* ptrPairs = CheckForPairs(array, 5, nPairsFound);
for(int i(0); i < nPairsFound; i++)
{
cout << ptrPairs[i] << endl;
}
if(ptrPairs)
{
delete[] ptrPairs;
ptrPairs = NULL;
}
return 0;
}
int* CheckForPairs(int array[] , int size, int& nPairsFound)
{
int *temp = NULL;
nPairsFound = 0;
int j = 0;
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
nPairsFound++;
}
temp = new int[nPairsFound];
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
{
temp[j] = i;
j++;
}
}
return temp;
}
You could use a std::unordered_set for a O(n) solution:
#include <unordered_set>
using namespace std;
bool hasMatchingElements(const int array[], int arraySize) {
unordered_set<int> seen;
for (int i = 0; i < arraySize; i++) {
int t = array[i];
if (seen.count(t)) {
return true;
} else {
seen.insert(t);
}
}
return false;
}
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
This loop will only compare two adjacent values so the loop will return false for array[] = {2,3,2,4,5}.
You need a nested for loop:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int unsortedArray[] = {2,3,2,4,5};
int size = 5;
for(int i=0;i<size-1;i++)
{ for(int j=i+1;j<size;j++)
{ if(unsortedArray[i]==unsortedArray[j])
{ printf("matching cards found\n");
return 0;
}
}
}
printf("matching cards not found\n");
return 0;
}
----EDIT------
Like Ben said, I should mention the function above will only find the first instance of 2 matching cards but it can't count how many cards match or if there are different cards matching. You could do something like below to count all the number of matching cards in the unsortedArray and save those values into a separate array. It's messier than the implementation above:
#include <iostream>
#include <stdio.h>
#include <stdbool.h>
#defin NUM_CARDS 52;
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int N,i,j;
cin>>N;
int unsortedArray[N];
for(int i=0;i<N;i++)
cin>>unsortedArray[i];
int count[NUM_CARDS]={0};
int cnt = 0;
for( i=0;i<N-1;i++)
{
for( j=i+1;j<N;j++)
{ if(unsortedArray[i]==-1)
break;
if(unsortedArray[i]==unsortedArray[j])
{
unsortedArray[j]=-1;
cnt++;
}
}
if(unsortedArray[i]!=-1)
{
count[unsortedArray[i]]=cnt; //in case you need to store the number of each cards to
// determine the poker hand.
if(cnt==1)
cout<<" 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else if(cnt>=2)
cout<<" more than 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else
cout<<" no matching cards of "<<unsortedArray[i]<<" was found"<<endl;
cnt = 0;
}
}
I'm trying to delete all elements of an array that match a particular case.
for example..
if(ar[i]==0)
delete all elements which are 0 in the array
print out the number of elements of the remaining array after deletion
what i tried:
if (ar[i]==0)
{
x++;
}
b=N-x;
cout<<b<<endl;
this works only if i want to delete a single element every time and i can't figure out how to delete in my required case.
Im assuming that i need to traverse the array and select All instances of the element found and delete All instances of occurrences.
Instead of incrementing the 'x' variable only once for one occurence, is it possible to increment it a certain number of times for a certain number of occurrences?
edit(someone requested that i paste all of my code):
int N;
cin>>N;
int ar[N];
int i=0;
while (i<N) {
cin>>ar[i];
i++;
}//array was created and we looped through the array, inputting each element.
int a=0;
int b=N;
cout<<b; //this is for the first case (no element is deleted)
int x=0;
i=0; //now we need to subtract every other element from the array from this selected element.
while (i<N) {
if (a>ar[i]) { //we selected the smallest element.
a=ar[i];
}
i=0;
while (i<N) {
ar[i]=ar[i]-a;
i++;
//this is applied to every single element.
}
if (ar[i]==0) //in this particular case, we need to delete the ith element. fix this step.
{
x++;
}
b=N-x;
cout<<b<<endl;
i++;
}
return 0; }
the entire question is found here:
Cut-the-sticks
You could use the std::remove function.
I was going to write out an example to go with the link, but the example form the link is pretty much verbatim what I was going to post, so here's the example from the link:
// remove algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::remove
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove (pbegin, pend, 20); // 10 30 30 10 10 ? ? ?
// ^ ^
std::cout << "range contains:";
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
return 0;
}
Strictly speaking, the posted example code could be optimized to not need the pointers (especially if you're using any standard container types like a std::vector), and there's also the std::remove_if function which allows for additional parameters to be passed for more complex predicate logic.
To that however, you made mention of the Cut the sticks challenge, which I don't believe you actually need to make use of any remove functions (beyond normal container/array remove functionality). Instead, you could use something like the following code to 'cut' and 'remove' according to the conditions set in the challenge (i.e. cut X from stick, then remove if < 0 and print how many cuts made on each pass):
#include <iostream>
#include <vector>
int main () {
// this is just here to push some numbers on the vector (non-C++11)
int arr[] = {10,20,30,30,20,10,10,20}; // 8 entries
int arsz = sizeof(arr) / sizeof(int);
std::vector<int> vals;
for (int i = 0; i < arsz; ++i) { vals.push_back(arr[i]); }
std::vector<int>::iterator beg = vals.begin();
unsigned int cut_len = 2;
unsigned int cut = 0;
std::cout << cut_len << std::endl;
while (vals.size() > 0) {
cut = 0;
beg = vals.begin();
while (beg != vals.end()) {
*beg -= cut_len;
if (*beg <= 0) {
vals.erase(beg--);
++cut;
}
++beg;
}
std::cout << cut << std::endl;
}
return 0;
}
Hope that can help.
If you have no space bound try something like that,
lets array is A and number is number.
create a new array B
traverse full A and add element A[i] to B[j] only if A[i] != number
assign B to A
Now A have no number element and valid size is j.
Check this:
#define N 5
int main()
{
int ar[N] = {0,1,2,1,0};
int tar[N];
int keyEle = 0;
int newN = 0;
for(int i=0;i<N;i++){
if (ar[i] != keyEle) {
tar[newN] = ar[i];
newN++;
}
}
cout<<"Elements after deleteing key element 0: ";
for(int i=0;i<newN;i++){
ar[i] = tar[i];
cout << ar[i]<<"\t" ;
}
}
Unless there is a need to use ordinary int arrays, I'd suggest using either a std::vector or std::array, then using std::remove_if. See similar.
untested example (with c++11 lambda):
#include <algorithm>
#include <vector>
// ...
std::vector<int> arr;
// populate array somehow
arr.erase(
std::remove_if(arr.begin(), arr.end()
,[](int x){ return (x == 0); } )
, arr.end());
Solution to Cut the sticks problem:
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
// Cuts the sticks by size of stick with minimum length.
void cut(vector<int> &arr) {
// Calculate length of smallest stick.
int min_length = INT_MAX;
for (size_t i = 0; i < arr.size(); i++)
{
if (min_length > arr[i])
min_length = arr[i];
}
// source_i: Index of stick in existing vector.
// target_i: Index of same stick in new vector.
size_t target_i = 0;
for (size_t source_i = 0; source_i < arr.size(); source_i++)
{
arr[source_i] -= min_length;
if (arr[source_i] > 0)
arr[target_i++] = arr[source_i];
}
// Remove superfluous elements from the vector.
arr.resize(target_i);
}
int main() {
// Read the input.
int n;
cin >> n;
vector<int> arr(n);
for (int arr_i = 0; arr_i < n; arr_i++) {
cin >> arr[arr_i];
}
// Loop until vector is non-empty.
do {
cout << arr.size() << endl;
cut(arr);
} while (!arr.empty());
return 0;
}
With a single loop:
if(condition)
{
for(loop through array)
{
if(array[i] == 0)
{
array[i] = array[i+1]; // Check if array[i+1] is not 0
print (array[i]);
}
else
{
print (array[i]);
}
}
}