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; }
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)