Question

I am writing a lexer and I am using an array to strore the keywords and reserved words:

string keywords[20] = {

  "function",
  "if",
  "while",
  "halt",
};

I am trying to use :

bool isKeyword(string s)
{
  return find( keywords.begin(), keywords.end(), s ) != keywords.end();
}

but I am getting the error: "error: request for member 'end' in 'keywords', which is of non-class type 'std::string [20] {aka std::basic_string [20]}"

Was it helpful?

Solution

Plain arrays don't have methods, so you can't call begin() and end() on them. But you can use the non-member functions of the same name:

#include <alorithm> // for std::find
#include <iterator> // for std::begin, std::end

bool isKeyword(string s)
{
  std::find(std::begin(keywords), std::end(keywords), s ) != std::end(keywords);
}

If you don't have C++11 support, you can easily roll these functions out yourself, or use the size of the array to get the end iterator:

return std::find(keywords, keywords + 20, s ) != keywords + 20;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top