用于字符串的容器和用于匹配和计数的int型容器

Container for a string and int for matching and counting?

本文关键字:用于 int 字符串      更新时间:2023-10-16

在c++中,创建一个临时容器来存储字符串和int,就像c#字典那样,我可以很容易地将字符串键与另一个字符串匹配,并增加或减少输入值int,最简单的方法是什么?

容器的内容将来自一个字符串,其中每个由空格分隔的单词是一个键项,每个键的所有值都以0开头。

Dictionary<string, int> Options = new Dictionary<string, int>();
Options.Add("xyz", 0);
Options.Add("abc", 0);
Options.Add("dfg", 0);
然后我必须将它与user选项进行比较,例如:
if (Options.ContainsKey(user_opt))
    Options[user_opt]++;

我最初尝试使用向量,但由于我对c++的了解几乎为0,所以我基本上卡住了。

对于向量,这是我得到的

vector<string> Options;
boost::split(Options, m_StartMode, boost::is_any_of(" "));

使用std::mapstd::unordered_map存储键、值

std::map<std::string, int> Options;
Options.insert(std::make_pair("xyz", 0));
Options.insert(std::make_pair("abc", 1));

然后用map::find检查key是否存在:

std::map<std::string,int>::iterator iter;
iter = Options.find(user_opt);
if(iter != Options.end())
   iter->second++;

std::map