If you want to store all the element just once you can use STL set in c++
(a example of doing this in c
is also given below). It store a value no more than one time. You can declare a set like this:
set<int>sett;
To insert a value in set
sett.insert(6);
To print all the value in set:
for(auto a: sett){
cout<<a<<endl;
}
You can go to geekforgeek and cplusplus website for more information.
If you want to track a number is in array or not, you can do it efficiently like this:
Take a Boolean Array or Map and make it's all initial value false
. After scanning from the file, if the number is N than make the Nth index of Boolean Array or Map true
.
Now if you want to check number M is in the array or not. You can easily get this by checking if the Mth index of Boolean array or Map is true
or not in just O(1) time.
See the example bellow, this is done using Boolean array. Remember to declear the boolean array globally if the size of boolean array is to large. You can do this by using STL Map too in c++
. For learning more about SLT MAP visit cplusplus , cppreference, geeksforgeeks.
#include <stdio.h>
#include <stdbool.h>
bool mapp[999999999] = {false};
int main()
{
int i, n, t, m, ara[1000];
printf("Input the size of array: ");
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf("%d", &ara[i]);
mapp[ara[i]] = true;
}
printf("Input number of time you want to check a number in array or not: ");
scanf("%d", &t);
while(t--){
scanf("%d", &m);
if(mapp[m] == true)
printf("Number Exists\n");
else
printf("Number Not Exists\n");
}
}
You can also use this trick to don't include duplicate value in array. To do that, if the inputed number is 'a'. Check if mapp[a]
is already marked as true
or not. Include 'a' in array only and only is if mapp[a] != ture
. This little change will exclude all duplicate value from your array.
scanf("%d", &n);
j = 0;
for(i = 0; i < n; i++){
scanf("%d", &a);
if(mapp[a] != true){
mapp[a] = true;
ara[j++] = a;
}
}