Complementing what @Maniero already said, you can use the std::find
that is part of the algorithms
library to search if the element exists. The find
receives 3 values, the initial, final element, and the value to be searched.
Transposing this to your code would look like this:
#include <iostream>
#include <algorithm> // inclusão do header associado
using namespace std;
int main (void){
int e[5] = {10,20,30,40,50};
for (int i = 0; i <= 99; i++){
if (find(e, e + 5, i) != e + 5) cout << i << " ";
// ^---^----^----^---- utilização do find
}
}
See this example in Ideone
In this example the initial value was set by the pointer to the first element with e
, and the end set also with a pointer, but advancing the amount of elements sufficient to be next to the last, e + 5
.
As find
returns a pointer to the found element, or to the end if there is no equal element, you must compare if that pointer is at the end.
A more natural use of this language is to save the search result to a pointer / iterator and then use it when you want to access the found element:
for (int i = 0; i <= 99; i++){
int *pesq = find(e, e + 5, i);
if (pesq != e + 5) cout << *pesq << " ";
// ^--- imprime o valor encontrado com base no ponteiro devolvido
}
See this example also in Ideone
As indicated by @MarioFeroldi in comment, you can also use std::begin
and std::end
to get the start and end of a normal array. This makes the code more flexible because it only defines the size in a location:
int e[5] = {10,20,30,40,50};
for (int i = 0; i <= 99; i++){
int *pesq = find(begin(e), end(e), i);
// ^--------^
if (pesq != end(e)) cout << *pesq << " ";
// ^---
}
See it on Ideone
Another possible common solution in the world of C ++ and not C is to use
vector
to store the integers, which slightly changes how
find
has to be used:
#include <iostream>
#include <algorithm>
#include <vector> //vector também necessário agora
using namespace std;
int main (void){
vector<int> e = {10,20,30,40,50};
for (int i = 0; i <= 99; i++){
if (find(e.begin(), e.end(), i) != e.end()) cout << i << " ";
}
}
Example on Ideone
Now the start and end of the search was built based on the method begin
and end
of vector
that return iterators to the corresponding elements.
Note: The code examples given in this answer have been adapted from documentation