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

I have a vector that I am trying to execute. I get some kind of casting error, and I cannot combine the solution. I also want to find out if what I am doing is suitable for me to check if the 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;
}
+5
source share
3 answers

When you declare a variable with its default constructor, you do not put ()after it (although this is not necessary if you use newto allocate space in free storage). So this line:

std::vector<double> vec();

should become

std::vector<double> vec;

, , , , vec, std::vector<double>, .

, ( ). , , std::find:

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

, binary_search, , find, - , binary_search bool 't vec.end()). , algorithm, .

+22
std::vector<double> vec();

, vector, . vector. :

std::vector<double> vec;
+5

You can use std :: find to verify that the STL data structure contains a specific value.

+3
source

All Articles