Nagui
Nagui

Reputation: 13

C++: I got wrong results while using a class to search for a specific element in a vector

I am searching for a specif element K in a vector. Instead of getting 1 0 I got 0 0 When I used the same code directly in the main () without the class, I got right results.

#include <iostream>
#include <sys/resource.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> 
#include <sys/types.h>
#include <algorithm>
#include <vector>

using namespace std;

class Answer
{
public:
static bool exists(int ints[], int size, int k)
{
    std::vector<int> v( ints, ints + sizeof(ints)/sizeof(ints[0]) ) ;
   auto result1 = std::find(v.begin(), v.end(), k);

if (result1 != v.end()) {
    return true;
} else  {
    return false;
}


}
};

int main()
{
int ints[] = { -9, 14, 37, 102 };
cout << Answer::exists(ints, 4, 102) << endl; // 1
cout << Answer::exists(ints, 4, 36) << endl; // 0
return 0;
}

Upvotes: 0

Views: 55

Answers (1)

Swordfish
Swordfish

Reputation: 13134

You cannot obtain the number of elements in an array once you have passed it to a function since it will decay to a pointer. So instead of

std::vector<int> v(ints, ints + sizeof(ints) / sizeof(ints[0]));

use the 2nd parameter size:

std::vector<int> v(ints, ints + size);

As @WhozCraig pointed out in the comments to your question there is no need for a temporary vector since you can use std::find() on arrays perfectly fine:

class Answer
{
public:
    static bool exists(int ints[], int size, int k)
    {
        auto result = std::find(ints, ints + size, k);
        return result != ints + size;
    }
};

Upvotes: 2

Related Questions