Remove and shift array c++ - c++

I want to locate a specific item from an array and then shift the array to remove that item. I have a list of integers {1, 2, 3, 4, 5, 6, 7, 8, 9} and want to remove the integer 2.
Currently I am getting an error: storage size of ‘new_ints’ isn’t known on the line:
int new_ints[];
Not sure what this means or how can I fix this?
Here is my code:
int main() {
int tmp = 2;
int valid_ints[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int new_ints[];
new_ints = stripList(tmp, valid_ints);
for (int i = 0; i < sizeof(new_ints); i++)
cout << new_ints[i] << endl;
return 0;
}
int *stripList (int tmp, int valid_ints[]){
for (int i = 0; i < sizeof(valid_ints); i++){
for (int j = tmp; j < sizeof(valid_ints); j++){
valid_ints[j] = valid_ints[j+1];
}
}
return valid_ints;
}

Like what Ben said, it is highly recommended to use an vector if you would like to resize your array to fit in new elements.
http://www.cplusplus.com/reference/vector/vector/vector/
Here's my example: (note alternatively you can use vector::erase to erase undesired elements)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> valid_ints;
vector<int> new_ints;
int tmp = 2;
//read in elements
for(int i = 1; i <= 9; i++)
{
valid_ints.push_back(i);
}
//valid_ints will hold {1,2,3,4,5,6,7,8,9}
for(int i = 0; i < valid_ints.size(); i++)
{
//We will add an element to new_ints from valid_ints everytime the valid_ints[i] is NOT tmp. (or 2.)
if(valid_ints[i] != tmp)
{
new_ints.push_back(valid_ints[i]);
}
}
//Print out the new ints
for(int i = 0; i < new_ints.size(); i++)
{
cout << new_ints[i] << ' ';
}
return 0;
}
The resulting vector will be filled in this order:
{1}
{1,3} (skip 2!)
{1,3,4}
{1,3,4,5}
so on... until
{1,3,4,5,6,7,8,9}
So, the output would be:
1 3 4 5 6 7 8 9

In c++ size of an array must be known at compile time. Ie int new_ints[] is illegal. You will need to have a defined size ie new_ints[10]. (See here for more details) Or better yet, utilize the fantastic advantages of c++ and use a std::vector.

Related

How does a 2D array within another array work?

I am looking at my homework for c++ and having some trouble understanding a part of the code. The code is creating a 2d array and wants to know how many times the elements from 1-9 are repeated.
#include <iostream>
using namespace std;
const int r = 3;
const int c = 4;
void frequency (int a[r][c]);
int main() {
int elems [r][c] = {{1, 1, 3, 4}, {2, 3, 4, 5}, {6, 9, 9, 9}};
frequency(elems);
return 0;
}
void frequency(int a[r][c]){
int arr[10] = {};
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
arr[a[i][j]]++;
}
}
for(int i = 1; i < 10; i++){
cout << i << " is repeated " << arr[i] << " times." << endl;
}
}
I don't understand how the line arr[a[i][j]]++; works -- how does it act as a counter for elements that are repeated?
I don't understand how the line arr[a[i][j]]++; works -- how does it act as a counter for elements that are repeated?
int arr[10] = {}; is creating an int-array with 10 elements (indexed 0-9) all initialized to 0.
arr[a[i][j]]++; is (post-)incrementing an element of arr.
The element at which index? The one at index a[i][j].
You loop through every row in a (i.e. in elems) using i and through every column within that row using j; in essence looping through every element in the order they are spelled in the source code. You are using the numbers in array a to index into the array arr: The first two elements of elems are 1, thus you increment arr[1]. The third number in elems is 3, thus you increment arr[3], ...

replaces duplicate values in an array with -1 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 11 months ago.
Improve this question
Write a function that replaces duplicate values in an array with -1.
Assume that an array of positive numbers such as {1, 2, 5, 4, 2, 7, 1, 2} is passed to your function.
You must check duplicate values in this array and replace them with -1 except the first appearance.
Your final array of {1, 2, 5, 4, 2, 7, 1, 2} should look like {1,2,5,4,-1, 7, -1,-1}
this is my question can someone figure out ?
{
for(j=i+1; j<size; j++)
{
/* If any duplicate found */
if(arr[i] == arr[j])
{
/* Delete the current duplicate element */
for(k=j; k < size - 1; k++)
{
arr[k] = arr[k + 1];
}
/* Decrement size after removing duplicate element */
size--;
/* If shifting of elements occur then don't increment j */
j--;
}
}
}
In C++, you would do this exactly as you would do manually, with your brain.
Iterate over all elements in the array
Count the number of occurences of an element
If this element is more than one time present, then replace it.
For counting we will use a hash map, so an std::unordered_map. Please read here about that.
The very simple code would then look like this:
#include <iostream>
#include <vector>
#include <unordered_map>
int main() {
std::vector testData{ {1, 2, 5, 4, 2, 7, 1, 2} };
std::unordered_map<int, unsigned int> counter{};
for (int& i : testData) {
counter[i]++;
if (counter[i] > 1)
i = -1;
}
for (const int k : testData)
std::cout << k << ' ';
}
Maybe something like this:
#include <stdio.h>
#include <stdlib.h>
void replaceDuplicates(int *arr, int n)
{
int *differents = malloc(n * sizeof(n));
int iterator = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(arr[i] == differents[j])
{
arr[i] = -1;
}
}
if(arr[i] != -1)
{
differents[iterator++] = arr[i];
}
}
}
int main()
{
int arr[8] = {1, 2, 5, 4, 2, 7, 1, 2};
replaceDuplicates(arr, 8);
for(int i = 0; i < 8; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Note that I haven't tested this code that much. You should probably improve it
This code outputs:
1 2 5 4 -1 7 -1 -1

make an array where the number that i insert gets deleted and is replaced by a 0 at end of array using pointers

I'm making it in a 3x4 matrix form
Also I'm not sure how to use a pointer since the number that I want to change and replace is an arr[3][4] and not the usual arr[5]
using namespace std;
#include <iomanip>
int main(){
int i;
int j;
int *change;
int number; // not sure how to use the pointer to reference a [3][4] array //
int arr[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
for (int i = 0; i < 3; i++) // not sure if there is a way where i dont have to write every number and just have it go from 1 to 12 //
{
for (int j = 0; j < 4; j++)
{
cout << setw(8)<<arr[i][j] << ' '; // to make it look organized and aligned//
}
cout <<endl;
}
cout << "number" << ' ';
cin >> number; // i woud insert the number here//
cout << arr[3][4];
return 0;
}
and should appear like this (say i chose 6)
1 2 3 4
5 7 8 9
10 11 12 0
The operation that you want to do is natural for single dimensional ranges, and not for multi dimensional ones. There are standard algorithms to achieve your goal with a single dimensional range.
With range views, it's fairly simply to get a single dimensional view of the elements:
// flat view of the array
auto flat_arr = arr | std::ranges::views::join;
// move elements to overwrite the removed elements
auto remaining = std::ranges::remove(flat_arr, number);
// fill the ramaining space with zeroes
std::ranges::fill(remaining, 0);
Without using ranges, you could achieve the same by defining a custom iterator. Alternatively, you could use a single dimensional array, and transform two dimensional indices with a bit of math. Example:
constexpr std::size_t rows = 3, cols = 4;
int arr[rows*cols] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// move elements to overwrite the removed elements
auto last_it = std::remove(std::begin(arr), std::end(arr), number);
// fill the ramaining space with zeroes
std::fill(last_it, std::end(arr), 0);
for (std::size_t i = 0; i < rows; i++)
{
for (std::size_t j = 0; j < cols; j++)
{
std::cout
<< std::setw(8)
// transform 2D to 1D
<< arr[i * cols + j]
<< ' '
;
}
std::cout << '\n';
}

C++ array operations

I want from the program to add 3 to elements which are greater than 3 and print them. It takes so much time that I couldn't see the result. Also, when I change n to 8 in loops directly, it gives a result; however, it's not related with what I want. How can I correct this code and improve that?
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 3, 0, 5, -10};
int b[8];
int n= sizeof(a);
for( int i=1; i<=n; i++) {
if (a[i]>3) {
b[i] = a[i] + 3;
}
else {
b[i]= a[i];
}
}
for (int i = 1; i <= n; i++)
cout << b[i];
return 0;
}
The sizeof() function (int n = sizeof(a)) gives 32 because array 'a' contains 8 elements & each element is of 'int' type whose size is 4 byte in memory thats why it returns 32 in 'n' variable.so you must divide the value of 'n' with the size of integer.
Secondly the index of array starts with the zero '0' to one less than the length of array not with the 1 to length of array .
Try the below code ! I am also attach the output of the code .
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a[8] = { -5, 7, 1, 0, 3, 0, 5, -10 };
int b[8];
int n = sizeof(a)/sizeof(int);
for (int i = 0; i < n; i++) {
if (a[i]>3) {
b[i] = a[i] + 3;
}
else {
b[i] = a[i];
}
}
for (int i = 0; i < n; i++)
cout << b[i]<<endl;
return 0;
}
The statement in your program int n=size(a) returns the total bytes occupied in memory for a. i.e int occupies 4 bytes and a is an array contains 8 elements so 8X4 = 32 .but while accessing the array elements using loop you are specifying i<=n meains i<=32 but there is only 8 elements but you are trying to access 32 elements which indicates that you are trying to access the elements more than 8.
exeutes the following code
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 3, 0, 5, -10};
int b[8];
int n=sizeof(a);
cout<<"\n Value of n is : "<<n;
return 0;
}
Output
Value of n is : 32
if you specify the exact number of array size your program will work properly.
#include <iostream>
using namespace std;
int main()
{
int a[8] = {-5, 7, 1, 0, 6, 0, 8, -10};
int b[8];
for( int i=1; i<8; i++)
{
if (a[i]>3)
{
b[i] = a[i] + 3;
}
else
{
b[i]= a[i];
}
}
cout<<"\n Values in a array";
cout<<"\n -----------------\n";
for (int i = 1; i <8; i++)
cout << "\t"<<a[i];
cout<<"\n Values in b array";
cout<<"\n -----------------\n";
for (int i = 1; i <8; i++)
cout << "\t"<<b[i];
return 0;
}
OUTPUT
Values in a array
-----------------
7 1 0 6 0 8 -10
Values in b array
---------------
10 1 0 9 0 11 -10
I hope that you understand the concept.Thank you
Your int n = sizeof(a); doesn't works as you intend.
I think you want to get the size of array (i.e. 8).
But you gets the size in bytes of elements (e.g. 32, integer size or could be different depending of your system's architecture).
Change to int n = 8, will solve your problem.
Also note that for( int i=1; i<=n; i++) will get an "out of array" element.
Sizeof function gives the value of the total bits of memory the variable occupy
Here in array it stores 8 integer value that has 2bit size for each thus it returns 32

Sorting an array to another array C++

My program have to sort an array in another array.
When I run the program it prints 1 2 3 -858993460 5 -858993460 7.
I can not understand where the mistake is in the code.
#include <iostream>
using namespace std;
int main()
{
const int N = 7;
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int max = arr[0];
for (int i = 1; i < N; i++)
{
if (max < arr[i])
max = arr[i];
}
int sort_arr[N];
for (int j = 0; j < N; j++)
{
sort_arr[arr[j] - 1] = arr[j];
}
for (int i = 0; i < N; i++)
{
cout << sort_arr[i] << " ";
}
return 0;
}
Okay lets face the problems in your code.
The "weird" numbers you see there, came from the uninitialzied array sort_arr. What do I mean by uninitialized? Well sort_arr is a little chunck somewhere in your memory. Since a program usually does not clear its memory and rather claims the memory it used as free, the chunk of sort_arr may contain bits and bytes set by another program. The numbers occure since these bytes are interpreted as an integer value. So the first thing to do would be to initialize the array before using it.
sort_arr[N] = { 0, 0, 0, 0, 0, 0, 0 };
Now why did these numbers occure? Well you're probably expecting your algorithm to set all values in sort_arr which would result in an sorted array, right? Well but your algorithm isn't working that well. See this line:
sort_arr[arr[j] - 1] = arr[j];
What happens when j is 1? arr[1] is then evaluated to 17 and 17 - 1 equals 16. So sort_arr[arr[1] - 1] is the same as sort_arr[16] which exceeds the bounds of your array.
If you want to program a sorting algorithm by your self than I would recommend to start with an simple bubble sort algorithm. Otherwise, if you only need to sort the array have a look at the algorithm header. It is fairly simple to use:
#include <iostream>
#include <algorithm>
#include <iterator> // << include this to use begin() and end()
using namespace std;
int main()
{
const int N = 7;
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int sort_arr[N] = { 0, 0, 0, 0, 0, 0, 0 };
copy(begin(arr), end(arr), begin(sort_arr));
sort(begin(sort_arr), end(sort_arr));
for (int i = 0; i < N; i++)
{
cout << sort_arr[i] << " ";
}
cout << endl;
}
By the way. You're looking for the biggest value in your array, right? After you have sorted the array sort_arr[N - 1] is the biggest value contained in your array.
If you want to sort a array into another array then one way is you make a copy of the array and then use the sort function in the standard library to sort the second array.
int arr[10];
int b[10];
for(int i=0;i<10;i++)
{
cin>>arr[i];
b[i]=arr[i];
}
sort(b,b+10);
// this sort function will sort the array elements in ascending order and if you want to change the order then just add a comparison function as third arguement to the sort function.
It seems that you think that sort_arr[arr[j] - 1] = arr[j] will sort arr into sort_arr. It won't.
Sorting is already written for you here: http://en.cppreference.com/w/cpp/algorithm/sort You can use that like this:
copy(cbegin(arr), cend(arr), begin(sort_arr));
sort(begin(sort_arr), end(sort_arr));
Live Example
My guess is this is an attempt to implement a type of counting sort. Note that variable length arrays aren't normally allowed in C++ or some versions of C. You could use _alloca() to allocate off the stack to get the equivalent of a variable length array: int * sort_arr = (int *)_alloca(max * sizeof(int)); .
#include <iostream>
using namespace std;
int main()
{
const int N = 7;
// assuming range of values is 1 to ...
int arr[N] = { 3, 17, 2, 9, 1, 5, 7 };
int max = arr[0];
for (int i = 1; i < N; i++)
{
if (max < arr[i])
max = arr[i];
}
int sort_arr[max];
for (int i = 0; i < max; i++)
{
sort_arr[i] = 0;
}
for (int j = 0; j < N; j++)
{
sort_arr[arr[j] - 1]++;
}
for (int i = 0; i < max; i++)
{
while(sort_arr[i])
{
cout << i+1 << " ";
sort_arr[i]--;
}
}
return 0;
}