1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
#include <iostream>
void remov_item(int arr[],int item,std::size_t& used_len);
bool add_item(int arr[],int item,std::size_t& used_len,std::size_t real_len);
int search_item(int arr[],int item,int used_len);
void print_array(int arr[],std::size_t used_len);
int main()
{
int arr[]{1,2,3,4,5,6,7,8,9,10,11,12,13,15,15,16,17,18,19,20,0,0,0,0,0};///think of 0 as blank
std::size_t real_len = 24;///can't change
std::size_t used_len = 20;///can change, denotes the # of items placed in arr
int to_remov = 4;
std::cout<<"used length: "<<used_len<<std::endl;
print_array(arr,used_len);
std::cout<<"removing "<<to_remov<<std::endl<<std::endl;
remov_item(arr,to_remov,used_len);
std::cout<<"used length: "<<used_len<<std::endl;
print_array(arr,used_len);
std::cout<<"adding: "<<30<<std::endl;
if(add_item(arr,30,used_len,real_len))
std::cout<<"element added successfully\n\n";
else
std::cout<<"can't add elements array full\n\n";
std::cout<<"adding: "<<70<<std::endl;
if(add_item(arr,70,used_len,real_len))
std::cout<<"element added successfully\n\n";
else
std::cout<<"can't add elements array full\n\n";
std::cout<<"used length: "<<used_len<<std::endl;
print_array(arr,used_len);
}
int search_item(int arr[],int item,int used_len)
{
for(int i=0; i<used_len; i++)
{
if(arr[i] == item)
return i;
}
return -1;///not found
}
void remov_item(int arr[],int item,std::size_t& used_len)
{
auto index = search_item(arr,item,used_len);
for(std::size_t j = index; j < used_len-1; j++)
{
arr[j] = arr[j+1];
}
arr[used_len] = 0;///blank now
if(index!= -1)
--used_len;
}
void print_array(int arr[],std::size_t used_len)
{
for(std::size_t i = 0; i<used_len; i++)
{
std::cout<<arr[i]<<" ";
}
std::cout<<"\n\n";
}
bool add_item(int arr[],int item,std::size_t& used_len,std::size_t real_len)
{
if(used_len == real_len)///array full
return false;
arr[used_len] = item; ///add item
++used_len;
return true;
}
|