How to clear out element inside an array? - c++

I want to clear out all the element inside my array but I don't know how to automatically clear it out. is there a function for it? Like the clear() for lists??
int array[5] = {2,5,4,8,6};
then I want to clear out everything and add a new set of values

Your question isn't valid because you can't clear out an array. An array has a fixed size and there always will be some value in it.
If you want to re-use an array, just overwrite the existing values.
Perhaps consider using std::vector. Using clear() function, you can clear all the values from the std::vector.
Learn about std::vector Here

To clear an array means to set all values to T() that for arrays of fundamental arithmetic types is equivalent to set all elements to zeroes.
You can do it in several ways. The first one is to use standard C function std::memset declared in header <cstring>. For example
#include <iostream>
#include <cstring>
int main()
{
int array[] = { 2, 5, 4, 8, 6 };
const size_t N = sizeof( array ) / sizeof( *array );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
std::memset( array, 0, N * sizeof( int ) );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
Another way is to use standard algorithm std::fill declared in header <algorithm>. For example
#include <iostream>
#include <algorithm>
int main()
{
int array[] = { 2, 5, 4, 8, 6 };
const size_t N = sizeof( array ) / sizeof( *array );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
std::fill( array, array + N, 0 );
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
In the both cases the program output is
2 5 4 8 6
0 0 0 0 0
If you need a variable length array then use standard container std::vector<int>.
For example
#include <iostream>
#include <iomanip>
#include <vector>
int main()
{
std::vector<int> array = { 2, 5, 4, 8, 6 };
for ( int x : array ) std::cout << x << ' ';
std::cout << std::endl;
array.clear();
std::cout << "array is empty - " << std::boolalpha << array.empty() << std::endl;
return 0;
}
The program output is
2 5 4 8 6
array is empty - true
Instead of array.clear(); there could be also used array.resize( 0 ); in the program.

Related

Unexpected results with array and array as argument [duplicate]

This question already has an answer here:
When passing an array to a function in C++, why won't sizeof() work the same as in the main function?
(1 answer)
Closed 1 year ago.
Forgive me for this possibly dumb question. Consider this:
int foo(int* arr) {
std::cout << arr << "(" << sizeof(arr) << ")";
}
int main()
{
int x[] = {0, 1, 2, 3, 4};
foo(x);
std::cout << " " << x << "(" << sizeof(x) << ")";
}
Output: 0x7c43ee9b1450(8) 0x7c43ee9b1450(20) - Same address, different size.
My understanding is that the function argument is an address specific to the first element of the array, so the size is 8 bytes, and the same should be true for the variable in main too; So how come the size of the variable outside of the function represent the whole array (4 bytes int times 5 elements = 20)? How could I possibly determine from inside the function how large an array actually is?
This is because the types are not the same inside and out side the function.
If you make sure the type is the same inside and outside the function you should get the same result.
int foo(int (&arr)[5])
{
std::cout << arr << "(" << sizeof(arr) << ")";
return 0;
}
The problem is that arrays decay into pointers at the drop of a hat. So if you pass an array to a function it will easily be converted into a pointer. That is what is happening here.
int foo(int* arr)
// ^^^^ Notice this is not an array.
// It is simply a pointer to an integer
// The array has decayed into a pointer to the
// first element in the array.
{
std::cout << arr << "(" << sizeof(arr) << ")";
return 0;
}
How could I possibly determine from inside the function how large an array actually is?
This is actually a real problem with C. In C they solved this by getting you to pass the size of the array as a second parameter:
int foo(int* arr, std::size_t size);
Then call it from main as:
foo(arr, sizeof(arr)/sizeof(arr[0])); // This always works as it done
// at compile time and not runtime
In C++ we don't usually use C-arrays but prefer std::vector or std::array as the size is easily retrievable. Generally we use a container type C as they are duck types of Container:
template<typename C>
int foo(C& container)
{
std::cout << "(" <<container.size() << ")";
return container.size();
}
When passing an array like that you loose ALL the size information.
So the called function is flying blind with regard to the array size.
In C++ is makes much more sense to use std::array (fixed size arrays), and std::vector (changing size arrays). It is much clearer what your intent is when you pass them to functions. There will be less mistakes and less memory access issues in your code.
I hope I don't scare you too much with the template version.
The vector variant is more easy, but may use a bit more memory at runtime.
#include <array>
#include <vector>
#include <iostream>
template<size_t N>
size_t foo(const std::array<int,N>& arr)
{
for (const auto n : arr) std::cout << n << " ";
std::cout << "(" << arr.size() << ")" << std::endl;
return arr.size();
}
size_t foo(const std::vector<int>& arr)
{
for (const auto n : arr) std::cout << n << " ";
std::cout << "(" << arr.size() << ")" << std::endl;
return arr.size();
}
int main()
{
std::array<int,5> x{ 0, 1, 2, 3, 4 };
std::vector<int> y{ 0, 1, 2, 3, 4 };
auto size_x = foo(x);
auto size_y = foo(y);
}

How can I calculate size of Array in C++

I had the online coding interview today and I really struggled while trying to calculate the size of the array.
Could you please help me with how can I measure the sizeof array here? I tried my best but no luck please help here.
#include<iostream>
#include<map>
#include<vector>
using namespace std;
void arraysize(int* a) {
cout << "size1: "<<sizeof(a) << endl;
cout << "size2: " << sizeof(a[0]) << endl;;
}
int main()
{
int array1[] = { 1,2,3,4,5,6,7,8 };
arraysize(array1);
return 0;
}
Result:
size1: 4
size2: 4
In most cases, when you pass an array to a function, the array will be converted to a pointer. This is called an array-to-pointer decay. Once this decay happens, you lose the size information of the array. That is, you can no longer tell the size of the original array from the pointer.
However, one case in which this conversion / decay will not happen is when we pass a reference to the array. We can take advantage of this property to get the size of an array.
#include<iostream>
template<typename T, size_t N>
size_t asize(T (&array)[N])
{
return N;
}
int main()
{
int array1[] = { 1,2,3,4,5,6,7,8 };
std::cout << asize(array1) << std::endl; // 8
return 0;
}
In the above case, to the template function asize, we pass a reference to an array of type T[N], whose size is N. In this case, it is array type int[8]. So the function returns N, which is size 8.
C style array's decay to pointer's when passed to a function like this.
The first cout statement is printing the size of a pointer on your machine.
The second cout statement is printing the size of an integer.
Use one of the following solutions in order to pass the size of the array to the function.
template<std::size_t N>
void ArraySize( int ( &array )[ N ] )
{
std::cout << "Array size: " << N << '\n';
}
void ArraySize( int* array, std::size_t size )
{
std::cout << "Array size: " << size << '\n';
}
template<std::size_t N>
void ArraySize( std::array<int, N>& array )
{
std::cout << "Array size: "<< array.size( ) << '\n';
}
sizeof(a) returns the number of bytes in array,
sizeof(int) returns the number of bytes in an int,
ergo
sizeof(a)/sizeof(int) returns the array length
Easiest way to get the size of an array:
#include <iostream>
using namespace std;
int main(void) {
int ch[5], size;
size = sizeof(ch) / sizeof(ch[0]);
cout << size;
return 0;
}
Output: 5
simply divide sizeof(array1) by sizeof(int). it will give you total element in array. because sizeof(array1) will give total bytes in the array. for example sizeof(array1) = int * 8 because your array is int so int is 4 byte answer is 4*8 = 32.Now you have to divide it again by 4 cause its in byte.
cout << "Size of the Array is : " << sizeof(array1)/sizeof(int) << endl;
put above code in your main function to get result

Can a vector::iterator also function as a vector

So I am trying to load a binary file into a Vector, so I can use it like a Buffer.
ifstream binaryFile;
vector<unsigned char> fileBuffer(istreambuf_iterator<char>(binaryFile), {});
vector<unsigned char>::iterator fileIter = fileBuffer.begin();
Now my question is, if I use the fileIter variable, can I access all the elements in the fileBuffer vector ?
I want to know, because I need to edit the contents of the fileBuffer only at certain Positions, that is why I am working with iterators in the first place.
In a nutshell, I want to know if the content of the vector fileBuffer will change, according to edits made to the fileIter with code like
*(fileIter + 2) = 'a';
I have researched this Topic but I have not yet found an answer.
The standard class template std::vector has a random access iterator. So you can use it the same way as a pointer. For example
fileIter[10] = 'A';
or
fileIter += 10;
and so on.
Here is a demonstrative program.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
for ( const auto &item : v ) std::cout << item << ' ';
std::cout << '\n';
auto it = v.begin();
it[1] = -it[1];
for ( const auto &item : v ) std::cout << item << ' ';
std::cout << '\n';
it += 2;
*it *= 10;
for ( const auto &item : v ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
Its output is
1 2 3 4 5
1 -2 3 4 5
1 -2 30 4 5

Reverse array with recursion C++

My main idea is to shrink they array from both sides . For example if the input is 1234 , wanna print 1234 and then 4321 (the reversed) .
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int reversedArray(int* x)
{
cout<< "*x out of while =" << *x <<endl ;
while( *x != 0 )
{
cout << "*x=" << *x << endl;
cout<< "====================== im in reversed =================" << endl ;
return reversedArray( x+1 );
}
cout<< "after return " << *x << endl;
}
int main ()
{
int Array[] = {10,2,3,4,8 ,0} ;
int* p_Array = Array;
reversedArray( Array );
}
After the "while" , why the functions that are in the stack, do not return to the next line ( " the --> cout<< "after return " <<*x <
void printReversed(int * x)
{
if (*x == 0) return;
std::cout << *x;
printReversed(x+1);
std::cout << *x;
}
The line:
return reversedArray( x+1 );
exits the function. So you never repeat the while or execute any of the code after the while if you go into the while. This makes the while effectively an if statement.
The code posted by Crazy Eddie does the job and Barmar explains the ineffectiveness of the while loop. I decided to post a non-recursive way to address the problem mentioned.
#include <iostream>
#include <vector>
using namespace std;
vector<int> reverseArray(vector<int>& arr) {
vector<int> ans;
int n = arr.size();
// insert all elements in the reverse order
for (size_t i = 0; i < n; i++) {
ans.push_back(arr[n-i-1]);
}
return ans;
}
int main ()
{
int array[] = {10, 2, 3, 4, 8, 0};
// convert into vector
vector<int> arr(array, array+6);
vector<int> rev = reverseArray(arr);
// merging the 2 arrays
arr.insert(arr.end(), rev.begin(), rev.end());
// printArray(arr) -- implement to fit your needs;
}
When you pass an int[] to a function it decays to an int* which is simply an address in memory. C++ a better plan would be to use copy_backward with an ostream_iterator:
copy_backward(Array, Array + sizeof(Array) / sizeof(*Array), ostream_iterator<int>(cout, " "))
Note that this method uses the actual size of the array, and does not depend upon a terminal element. Thus, no numbers are offlimits, and it's impossible to segfault by failing to provide the terminating element.
If you have access to C++11 you can simplify that a bit further to:
copy(crbegin(Array), crend(Array), ostream_iterator<int>(cout, " "))
Live Example

Is it possible to swap arrays of arbitrary size in C++?

I'm wondering if it's possible to swap the contents of two C++ arrays that are of different sizes (without using any predefined C++ functions)? My code is as follows:
#include <iostream>
#include <string>
using namespace std;
void swapNames(char a[], char b[])
{
//can be done with one temp; using two for clarity purposes
char* temp = new char[80];
char* temp2 = new char[80];
int x = 0;
while(*(b+x)!='\0')
{
*(temp+x) = *(b+x);
x=x+1;
}
x=0;
while(*(a+x)!='\0')
{
*(temp2+x) = *(a+x);
x=x+1;
}
x=0;
while(*(temp2+x)!='\0')
{
*(b+x) = *(temp2+x);
x=x+1;
}
x=0;
while(*(temp+x)!='\0')
{
*(a+x) = *(temp+x);
x=x+1;
}
}
int main()
{
char person1[] = "James";
char person2[] = "Sarah";
swapNames(person1, person2);
cout << endl << "Swap names..." << endl;
cout << endl << "Person1 is now called " << person1;
cout << "Person2 is now called " << person2 << endl;;
}
My initial idea was to pass in references to person1 and person2 themselves, store the data in temp variables, delete the memory allocated to them, and link them to newly created arrays with the swapped data. I figured this would avoid predefined memory limits. It seems, though, that passing in references(&) to arrays is very much not allowed.
The above works fine if person1 and person2 are of the same size. However, once we have names of different sizes we run into problems. I assume this is because we can't alter the memory block we allocated when we initially created person1 and person2.
Also, is it possible to create a new array in C++ without predefining the size? IE a way to create my temp variables without placing a limit on their sizes.
char person1[] = "James";
is just a shorthand for:
char person1[6] = "James";
You cannot later store more than 6 characters in person1. If what you really want are strings of varying lengths, I would suggest ditching C style strings in favor of the std::string standard library type:
#include <string>
#include <algorithm>
std::string person1 = "James";
std::string person2 = "Sarah";
swap(person1, person2);
If your book teaches C style strings before std::strings, you should consider getting a new book.
References to arrays are allowed, as long as the array is fixed size.
There's an easy answer instead of all the complex things you are considering. Just use a vector.
vector<char> a;
vector<char> b;
...
a.swap(b);
What could be easier?
Also vectors are the answer to your question, 'Also, is it possible to create a new array in C++ without predefining the size?'. You can create a vector and then resize it later (which is almost the same thing).
You should always prefer container classes over raw arrays. But, if you absolutely must use an array, you can certainly accomplish swapping without resorting to dynamically allocating the temporary array. Use templates to statically determine the type and size of the arrays being passed into the swap function.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
template<typename T, size_t N>
void swap_arrays( T(&left)[N], T(&right)[N] )
{
T temp[N];
// copy left to temp
std::copy( std::begin(left), std::end(left), std::begin(temp) );
// copy right to left
std::copy( std::begin(right), std::end(right), std::begin(left) );
// copy temp to right
std::copy( std::begin(temp), std::end(temp), std::begin(right) );
}
template<typename T, size_t N>
void swap_and_print( T(&left)[N], T(&right)[N] )
{
std::cout << "\nBefore swapping: \n";
std::cout << " Left:";
std::for_each( std::begin(left), std::end(left),
[]( T const& t ) { std::cout << " " << t; } );
std::cout << "\n Right:";
std::for_each( std::begin(right), std::end(right),
[]( T const& t ) { std::cout << " " << t; } );
swap_arrays( left, right );
std::cout << "\nAfter swapping: \n";
std::cout << " Left:";
std::for_each( std::begin(left), std::end(left),
[]( T const& t ) { std::cout << " " << t; } );
std::cout << "\n Right:";
std::for_each( std::begin(right), std::end(right),
[]( T const& t ) { std::cout << " " << t; } );
}
int main()
{
int foo1[] = {1,2,3,4,5};
int bar1[] = {6,7,8,9,10};
swap_and_print( foo1, bar1 );
char foo2[] = "James";
char bar2[] = "Sarah";
swap_and_print( foo2, bar2 );
}
Output:
Before swapping:
Left: 1 2 3 4 5
Right: 6 7 8 9 10
After swapping:
Left: 6 7 8 9 10
Right: 1 2 3 4 5
Before swapping:
Left: J a m e s �
Right: S a r a h �
After swapping:
Left: S a r a h �
Right: J a m e s �
Note: The weird character at the end of the second example is because the inputs are char arrays that include the terminating null character; and what you're seeing is its visual representation (since the code is printing it out as a character).