Hello, I am wondering about getting the size of an array and using it in a for loop. Is this possible? Code given below. In the first for loop I used 10 as the condition, since I know the array is size 10, but then I am wondering, what if I do not know the size of the array but i want the for loop to be less than the size of array, how do I work that? I try .length, but that does not work. Is there a way to do this? Thank you
I am learning from a book currently and only arrays have been covered. I have not went over vectors yet, This problem that I was solving was asked to be completed was with an array like i done. But I will look at vectors now to know what they are. Oh I know the sizeof operator, I read that in the book yesterday, but I thought that only worked for bytes though so thought that would not work for me. I will try that, thank you.
size of the array in bytes
---------------------------- = num locations
size of one location in bytes
this is using a lot of trouble to find what you already knew.
{ 1, 3, 5, 3, 5, 1, 2, 2, 6, 1 };
--1--2--3-4-5--6--7--8-9-10---
array is sized 10. you told it that when you made it :)
If arr is in scope, then for 1-dimensional arrays you can use std::size() [since C++17]. If arr is passed as a parameter of a function, then there is a clever template construct that is used to obtain the size of the passed array in the function.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
usingnamespace std;
int main()
{
int arr[] = {1, 3, 5, 3, 5, 1, 2, 2, 6, 1};
for (int i = 0; i < size(arr); ++i)
for (int j = i + 1; j < size(arr); ++j)
if (arr[i] == arr[j])
cout << arr[j] << endl;
}