C++ getting the size of an array - c++

I'm new to programming and I was wondering, how to get the size of an array, that is, get the size of how many elements are inside the array. For example if I declare an array of size 10, but only input 3 elements into the array, how would I determine the size of this array? If I don't know how many elements I placed in initially.

If you declare an array, e.g. int array[10], then its size is always 10 * sizeof(int). There is no way to know how many times you've accessed it; you'd need to keep track of that manually.
You should consider using container classes, e.g. std::vector:
std::vector<int> vec;
vec.push_back(5);
vec.push_back(10);
vec.push_back(42);
std::cout << vec.size() << "\n"; // Prints "3"

If you declare an old-style array of 10 elements, e.g. std::string words[10], the size of the array is always 10 strings. Even with the new style (std::array), it would be a fixed size.
You might be looking for a std::vector<>. This doesn't have a fixed size, but does have a .size() method. Therefore, if you add three elements to it, it will have .size()==3

to get the array size (in number of elements) assuming you do not know it in advance
use sizeof(a)/sizeof(a[0])
see the below example program. I used C but it should carry over to C++ just fine
#include <stdio.h>
int main(){
int a[10];
printf("%d elements\n",sizeof(a)/sizeof(a[0]));
return 0;
}
//output: 10 elements

There's several possible ways, but they depend on your definition.
If you know there is a value the user won't input (also known as a sentinel value), you can use a function like memset, to set the entire array to that unused value. You would then iterate through the list counting all the variables in the list that don't match that value.
The other way is to build your own array class, which counts whenever the array is modified (you'd have to overload the = and [] functions as appropriate).
You could also build a dynamically linked list, so as the user adds variables, the count can either be determined by walking the list or keeping count.
But, if you're taking the array as the basic array, with no idea as to it's actual starting state, and no idea what to expect from the user (given this is your program, this shouldn't occur), then generally speaking, no, there is known way to know this.

You maintain a counter variable count initialized to 0.
Whenever you are adding to array increment the count by 1.
Whenever you are removing from array decrement the count by 1.
anytime count will give you the size of the array.

Suggestion:
int[10] arr;
//init all to null
for (int i =0; i < 10; i++)
arr[i] = 0;
arr[0]=1;
arr[2]=5;
int sz = 0;
for (int j = 0; j < 10; j++)
if (arr[j] != 0) sz++;

Related

How to find it the array of size 'x' is completely filled or not, in C++?

int size = 10;
int arr[size] = {};
for(int i = 0; i < size; i++)
arr[i] = i;
Now how do I find if the array is filled or not in the code.
I know arr[size - 1] = 9, but what is arr[size] and beyond?
How do i compare arr[size] == ? using if statement, or is there another way? I am using ubnutu and this is the compiler g++ (Ubuntu 9.3.0-10ubuntu2) 9.3.0.
When you use raw arrays, it is your responsibility to handle that memory and keep track of what has been written.
This sounds like a good usecase for a std:vector instead. Especially by making use of its reserve(size) function.
With reserve you tell how much memory to keep for your data and then you can fill that array with push_back(content), retrieving the current number of filled elements with size() (of course reserve is just an optimization to avoid re-allocating the memory because even without it, a vector will dynamically grow).
Now how do I find if the array is filled or not
All arrays are always "filled". An array of N elements contains N elements and no less.
An element of trivial type could have an indeterminate value. There is no way to find whether a value is indeterminate. The behaviour of reading an indeterminate value is undefined.
In your example, you value initialised the array, so it is filled with value initialised elements (before the loop where you change the values). Which in case of int means that the array is filled with zeroes. You can test whether an element is zero or not like this:
if (arr[i])
// not zero
else
// is zero
but what is arr[size] and beyond?
There is no "arr[size] and beyond" because those indices are outside the bounds of the array. The behaviour of accessing values outside the bounds of an array is undefined.

How to delete columns of dynamic array in C++

I need help tring to delete columns of 2D array in C++. I've tried the operation by making a copy of the array. It succeeded only from the start to middle or the middle to the end of array. witch algorithm to jump unwanted columns in the array when making copy.
Because of dynamic arrays so the varable of the array is pointer for the first value so you can't get the size or even use sizeof to get the size , but there's no case where you use dynamic arrays witout knowing the size , either fixed or in runtime throw varable
This probably isn't the best way to do this but its' a potential solution
int removeColumn(int a){
vector<vector<int>> ret(M);
int i = 0;
for(vector<int> temp : Arr){
vector<int> tempp(N-1);
copy(temp.begin(), temp.begin()+a, tempp.begin());
copy(temp.begin()+a+1,temp.end(),tempp.begin()+a);
ret[i] = tempp;
i++;
}
Arr = ret;
return 0;
}
Essentially you iterate over each row and use two copy statements to copy from the beginning to an index and from said index + 1 to the end. I'm sure there's a way to do this more elegantly, you could try looking at for_each loops however I doubt you could do it exclusively with copy. Tested it with this code.
https://repl.it/repls/PrettyTerrificOmnipage
Hope this helps

How to count the number of elements in an predefined array

I want to count the actual number of elements in the array.
but if I use sizeof() statement it gives me the size of array. not the number of elements present.
int main()
{
int a[10],n;
a[0]=1;
a[1]=5;
a[2]=6;
n=sizeof(a)/sizeof(a[0]);
cout<<"The size of array " <<n;
}
Here it gives me the n value as 10 not 3. Please suggest me a way to derive the number of elements without affecting the performance.
int a[10]; // This would allocate 10 int spaces in the memory;
a[0] = 1; // You are changing whats inside the first allocated space, but you are not changing the number of items in your C array.
Solution 1 (Easy) :
#include <vector>
vector<int> a;
a.push_back(1);
a.push_back(2);
size_t size = a.size(); // to get the size of your vector. would return 2. size_t is the actual type returned by size() method and is an unsigned int.
Solution 2 (Complicated) :
You could create an int variable that you could call e.g. numberOfElements and update it each time you add an element.
This solution is actually used in the implementation of the vector class.
As it have been already mentioned, you should use std::vector or std:array to achieve this behaviour. Declaring simple array means you allocate enough memory on the heap. There is not a way to determine whether this memory is "occupied" with something valid or not, since there is always something (after allocation there are random values on each index of the array).

C++ How to create a dynamic array of vectors?

I'm having problem initialising an array of std::vectors.
I'm declaring and initialising it like this:
vector<component_change*>* _changes;
_changes = new vector<component_change*> [numThreads];
in the hope that it's in the same form as this:
int * foo;
foo = new int [5];
but when I hit a breakpoint after the initialisation, _changes' size is 0.
What am I doing wrong and how can I fix it?
I don't want to use a vector of vectors as the number I need remains constant throughout the program but depends on the current hardware. And I'm not just looking for a single vector (Each vector will be used by a different thread then merged when the threads have finished their tasks).
Thanks guys! :)
Your program is correct. But you misinterpreted the debugger. _changes's size is not 0, but the first vector in your array (the one _changes points at) is empty. Thats because the debugger does not know if _changes points at a single element or an array (in that case the compiler would not know how many elements are in that array). Simply use a vector and call std::vector::shrink_to_fit.
If the size can be determined at compile time use a std::array. If the size is a run-time argument then use a vector and don't change the size of the container.
Are you interested in have a vector for each thread, or a vector containing items used by each thread? I assumed the later, but my answer could be adapted.
This is using a statically sized array; (this syntax is close).
const int NUMBER_OF_THREADS = 5;
component_change* _changes[NUMBER_OF_THREADS] =
{
new component_change(1),
new component_change(2),
new component_change(3),
new component_change(4),
new component_change(5)
}
If the number of threads is dynamic, you will have to use a new...
int NUMBER_OF_THREADS = system.getThreadCount();
component_change* _changes = new component_change[NUMBER_OF_THREADS];
for (int i = 0; i < NUMBER_OF_THREADS; i++)
{
_changes[i] = new component_change(i+1);
}
If you want to a std::vector:
int NUMBER_OF_THREADS = system.getThreadCount();
std::vector<component_change*> _changes;
_changes.reserve(NUMBER_OF_THREADS);
for (int i = 0; i < NUMBER_OF_THREADS; i++)
{
_changes.push_back(new component_change(i+1));
}
I think you're kind of mislead, this size that you are reading belongs to the vector in the first element of the array. Its size is equal to 0 since no elements have been inserted in the vector yet.
new vector is usually wrong.
You should use, with most preferred if possible first,
std::vector<component_change> _changes(numThreads);
or
std::vector<std::unique_ptr<component_change>> _changes(numThreads);
or
std::vector<component_change*> _changes(numThreads);
or if each element of the vector should itself contain an array of components (it's not clear in your question)
std::vector<std::vector<**component_change**>> _changes(numThreads);
Declaring the component as one of the above ways, depending on your needs.
Note that the pointers begin not pointing to anything. You'd have to allocate the individual components as a separate step.
The following creates an array of numThreads vectors, not a vector of numThread elements.
new vector<component_change*> [numThreads]

Array as parameter, variable confusion

Ok, so I was getting some pretty off course answers so I thought I would edit this post and add the notes from the textbook for clarity:
Sometimes, the number of elements in the array might be less than the size of the array. For example, the number of elements in an array storing student data might increase or decrease as students drop or add courses. In such situations, we want to process only the components of the array that hold actual data. To write a function to process such arrays, in addition to declaring an array as a formal parameter, we declare another formal parameter specifying the number of elements in the array, as in the following function:
void initialize(int list[], int listSize)
{
int count;
for (count = 0; count < listSize; count++)
list[count] = 0;
}
The first parameter of the function initialize is an int array of any size. When the function initialize is called, the size of the actual array is passed as the second parameter of the function initialize.
Ok, now that I posted the entire example with textbook notes in it, my confusion is why they set the array to zero. The notes give me the impression that this function is allowing a user to use the array for any size that they wish because the size is set to zero which (I am guessing here) allows the user to pick any size array they want? and it will just reset every time back to zero so if you need more or less units for the next time, it will be default to zero so you can fill it again?
you said:
I know the function initialize is used to determine the value of the
array list by passing the value of the array to listsize
no. it's not true. this function is not to determine something but to INITIALIZE all the array (up to listsize index, btw: it might be dangerous since you can pass listsize greater than this list size in fact) with 0.
and
by passing the value of the array to listsize
no! listsize is here not the value of element, it is array size, look at "for" loop #Jason xD.
have you tried to call this function on some array with some listsize?
If your code was properly formatted, it might be more apparent that the statement list[count] = 0; gets executed each time through your for loop.
That is, it sets an element to zero each time through the loop. The result is that after the loop is complete, all elements in the array will be set to zero.
If you are talking about the "count = 0", then:
The more usual syntax is:
for(int blah = 0; blah < max; blah++)
But there's no reason why 'blah' has to be declared inside the for() statement itself:
int blah;
for(blah = 0; blah < max; blah++)
...is also acceptable.
Or:
int blah = 0;
for( ; blah < max; blah++)
Sometimes (but not in your example) it's desired to have 'blah' exist beyond the scope of the for() statement, so you can do something with it afterward:
int fileNum = 0;
for( ; fileNum < maxFiles && file_exists(fileNum); fileNum++)
{
//...do something...
}
int lastFileWas = fileNum; //Either it's 'maxFile', or the first file that didn't exist.
Another reason for putting variables outside of the for() statement, is when variables are really really large, and it would make the code easier to read if it's outside of the statement:
std::vector< std::pair<std::string, int> >::iterator myIterator = myVector.begin();
for( ; myIterator != myVector.end(); myIterator++)
This would be very messy if it was inside the for-statement itself (std::vector< std::pair >::iterator is a very long variable name to write out that would be messy to cram into a for() statement). (Though this is less a problem with C++11's 'auto' keyword).
If you are talking about the "list[count] = 0;", then:
With arrays, to assign a value, you "index into" the array using the square brackets (called the 'subscript operator'), and you can access individual variables (called 'elements') held in the memory of the array:
int myArray[10]; //10 integers in a block of memory.
myArray[0] = 5; //Accessing the first element in the block of memory.
myArray[3] = 17; //Accessing the fourth element in the block of memory.
In general:
Since you are using C++, you usually (90% of the time) would be better off using a std::vector. Arrays are rather odd, because they are very similar to pointers to blocks of memory, and can't be treated like regular variables. A std::vector, aside from many other benefits, wraps the array so you can treat it like a regular variable (because a vector is one).
Another quick way of accomplishing the same thing:
memset(list, 0, sizeof(int)*listSize);
This gets the whole block of memory allocated to list by calculating the size of the data type times the number of elements and setting it all to 0.
It is doing what it says, it is initializing. In this case the method is just setting every element of list to 0. It is probably more clear if you add braces:
for (count = 0; count < listSize; count++)
{
list[count] = 0;
}
So based on your updated post, the book's description is saying 1) You may not want to process the whole array because only a portion of it may have valid data 2) In order to write functions to process arrays that behave this way, functions that process these array's must not only take the array as a parameter but also the number of valid elements. 3) We are going to provide an example function initialize which follows the rules we just described BUT nothing in the text actually speaks to end result of initialize.
My above description as well as the other posts provide an accurate description of initialize.