c++数组和查找函数
C++ array and find functions
我正在编写一个词法分析器,我使用数组来存储关键字和保留字:
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;
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- 使用用户定义的函数查找数字的幂时出现问题
- 如何处理具有不同类的成员函数的函数查找表?
- 如果我们没有在 C++ 中传递大小变量,则通过函数查找数组的大小
- 使用用户定义的函数查找完美数时出现浮点异常错误
- 使用 lambda 函数查找 std::unordered_map 中的最小值
- 重载函数查找轮廓的实例与参数列表不匹配
- 使用C++中的割线函数查找根
- JNA 程序函数查找失败
- 通过 C 加加号中的函数查找中位数
- 试图通过函数查找数组的最大值和最小值,其中数组值由用户输入
- xlC模板函数问题的静态函数查找
- 使用线程函数查找 2D 数组中的最大条目
- 如何在cpp中使用std::regex_replace()函数查找和替换
- 数组函数查找最大值
- 使用' stdio.h '函数查找模板和名称
- CPP字符串构造函数查找并附加空字符