How do I check if a value is contained in a vector? C++

MintGrowth picture MintGrowth · May 14, 2011 · Viewed 31.3k times · Source

I have a vector that I am trying to perform a contains function on. I am receiving some sort of casting error and I can't piece together a solution. I am also wanting to know whether or not what I am doing is the appropriate way to check if a vector contains a value.

Here is the code:

#include "stdafx.h"
#include <vector>

static void someFunc(double** Y, int length);
static bool contains(double value, std::vector<double> vec);

int main()
{
    double doubleArray[] = { 1, 2, 3, 4, 5 };
    double *pDoubleArray = doubleArray;
    int size = sizeof doubleArray / sizeof doubleArray[0];

    someFunc(&pDoubleArray, size);

    return 0;
}
static void someFunc(double** Y, int length)
{   
    std::vector<double> vec();

    for(int i = 0; i < 10; i++)
    {
        //error: 'contains' : cannot convert parameter 2 from 'std::vector<_Ty> (__cdecl *)(void)' to 'std::vector<_Ty>'
        if(contains(*(Y[i]), vec)) 
        {
            //do something
        }
    }

}
static bool contains(double value, std::vector<double> vec)
{
    for(int i = 0; i < vec.size(); i++)
    {
        if(vec[i] == value)
        {
            return true;
        }
    }

    return false;
}

Answer

Seth Carnegie picture Seth Carnegie · May 14, 2011

When you declare a variable with it's default constructor, you don't put () after it (although it's optional when you use new to allocate space on the free store). So this line:

std::vector<double> vec();

should become

std::vector<double> vec;

If you leave it as you did, it thinks that line is a function prototype of a function called vec taking no parameters and returning a std::vector<double>, which is why you're getting a compiler error.

And yes, your code for finding an item will work (it's called a linear search). Also if you want to, you can use std::find:

if (std::find(vec.begin(), vec.end(), value) != vec.end())
    // found value in vec

If your vector is in sorted order, you can also use binary_search which is much faster than find, and the usage is the same except binary_search returns a bool instead of an iterator (so you don't need to test it against vec.end()). Make sure you include the algorithm header if you use either of these.