home   articles   tags   browse code   

C++ in_array function


 

This in_array function goes along with our other articles, gradually implementing the php api based on the C++ Standard Template Library.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

bool in_array(const string &needle, const vector< string > &haystack);

int main(int argc, char *argv[])
{

    vector< string > custom;

    custom.push_back("Apple");
    custom.push_back("Orange");
    custom.push_back("Cherry");

    if (in_array("Grape", custom))
        cout <<"Grape in list"<<endl;
    else
        cout <<"Grape not found"<<endl;

    if (in_array("Orange", custom))
        cout <<"Orange in list"<<endl;
    else
        cout <<"Orange not found"<<endl;
    return 0;
}

bool in_array(const string &needle, const vector< string > &haystack)
{
    int max=haystack.size();

    if (max==0) return false;

    for(int i=0; i<max; i++)
        if (haystack[i]==needle)
            return true;
    return false;
}
 

Tags: c++
 


 

 



Related Articles
 


home  |  privacy policy  |  terms of use  |  contact  


©2012, Zedwood.com

zedwood.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com