Using find

so I am supposed to be using find in order to check if the value of a given number is in my array here is what I have

1
2
3
4
 
int a[] = {1, 2, 3, 4, 5};
int* first = a + 1;
int* limit = first + 3;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 

 int* find(int* first, int* limit, int value);


 while  (first != limit)
 {
    if(first = 4)
    {return first;
    std::cout<<&first;

    }
    else
 {return limit;
 std::cout <<&limit;

 }


I keep getting errors
I know I can't directly see if a pointer is equal to an integer but I am completely lost
closed account (LUf3AqkS)
I wrote an example that hopefully explains what you are trying to do. There is a template function in <algorithm> std::find that you could use in the same way as you would call this function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

int* find(int* first, int* last, int val)
{
    while(first != last)
    {
        if(*first == val) //dereference pointer, is it the same as val?
            return first; //found the element so return a pointer to it

        ++first; //make 'first' point to the next element
    }

    return last; //val wasn't found
}

int main()
{
    int a[] = {1, 2, 3, 4, 5}; //array of 5 elements
    int* last = a + 5; //a+5 is one past the last element in a[]
    int* p = find(a, last, 3); //find the value 3 in a[]

    //if p is equal to one past the last element in a[], the element wasn't found
    if(p != last)
        std::cout << "found: " << *p << '\n';
    else
        std::cout << "not found\n";
}
Last edited on
You're a life saver! I tried following the template like you said but it wasnt making any sense. Thank you!
Topic archived. No new replies allowed.