-3

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]}"

  • 3
    before trying to make a compiler (I suppose that's why you're writing a lexer), you should at least familiarize yourself with the **very basic** concepts of the language you are using. – The Paramagnetic Croissant May 11 '14 at 12:05

1 Answers1

1

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;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • In fact I do not have C++11 suppost and with the .end I am getting the error: request for member 'end' in 'keywords', which is of non-class type 'std::string [20] {aka std::basic_string [20]}'again – user3599420 May 11 '14 at 12:10
  • @user3599420 The second solution should work without C++11. The errors you are getting are explained in the first line of this answer. – juanchopanza May 11 '14 at 12:11
  • the first line is saying that I can't use being and end with arrays, so how can I use .end in the last line? can you please explain further & thanks for your time – user3599420 May 11 '14 at 12:13
  • @user3599420 Sorry, I hadn't fixed that part. It is part of the same problem, and has the same solution. I fixed it now. – juanchopanza May 11 '14 at 12:14
  • Thanks so much! the +20 is used to loop till the end of the array am I right? – user3599420 May 11 '14 at 12:15
  • @user3599420 It gives a pointer to one-past the end of the array. Standard library algorithms use open ranges like that. – juanchopanza May 11 '14 at 12:17