C ++向量(而不是数组) [英] C++ vectors (instead of arrays)

查看:68
本文介绍了C ++向量(而不是数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写词法分析器,并将关键字和保留字存储在如下数组中:

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");

但是在这种情况下,我需要为向量修改isKeyword方法,并返回true或false.

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

推荐答案

#include <algorithm>

//...

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

如果可以对向量进行排序,则可以使用标准算法std::binary_search

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

例如

#include <algorithm>

//...

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

这篇关于C ++向量(而不是数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆