Question

I am writing a lexer and I stored the keywords and reserved words in an array like below:

string keywords[20] = {

  "and",
  "or",
  "while",
  "not",
  "if",
  "read",
  "write",
  "set",
};

I found that I could use vectors as :

vector<string> keyword_list;
keyword_list.clear();

keyword_list.push_back("and");
keyword_list.push_back("or");
keyword_list.push_back("not");

However in this I need isKeyword method be modified for a vector and returns true or false .

Was it helpful?

Solution

#include <algorithm>

//...

bool isKeyword( const std::string &s )
{
   return ( std::find( keyword_list.begin(), keyword_list.end(), s ) != keyword_list.end() );
}

If the vector would be sorted then you could use standard algorithm std::binary_search

For example

#include <algorithm>

//...

bool isKeyword( const std::string &s )
{
   return ( std::binary_search( keyword_list.begin(), keyword_list.end(), s ) );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top