c++数组和查找函数

C++ array and find functions

本文关键字:函数 查找 数组 c++      更新时间:2023-10-16

我正在编写一个词法分析器,我使用数组来存储关键字和保留字:

string keywords[20] = {
  "function",
  "if",
  "while",
  "halt",
};

我正在尝试使用:

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

但我得到错误:"错误:请求'关键字'中的成员'end',这是非类类型'std::string[20]{又名std::basic_string [20]}"

普通数组没有方法,因此不能在它们上调用begin()end()。但是您可以使用同名的非成员函数:

#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);
}

如果你没有c++ 11的支持,你可以很容易地自己推出这些函数,或者使用数组的大小来获得结束迭代器:

return std::find(keywords, keywords + 20, s ) != keywords + 20;