一個簡單的字串查詢程式

鍾超發表於2011-03-18

FILE 1: find.h

#ifndef HEAD_H_INCLUDED #define HEAD_H_INCLUDED #include <vector> using namespace std; template <typename elem_type> const elem_type *find(const vector<elem_type> &vec, const elem_type &value) { for(unsigned int ix = 0; ix < vec.size(); ++ix) { if(vec[ix] == value) { return &vec[ix]; } } return 0; } #endif // HEAD_H_INCLUDED

FILE 2: main.cpp

#include <vector> #include <string> #include <iostream> #include "head.h" using namespace std; int main(void) { const int a_size = 5; const string a_string[a_size] = {"Gold", "Wood", "Water", "Fire", "Earth"}; const string tag = "Wood"; const vector<string> vec(a_string, a_string + a_size); cout << *find(vec, tag) << endl; return 0; }

相關文章