gpt4 book ai didi

c++ - 比较 std::strings 的最佳方法

转载 作者:IT老高 更新时间:2023-10-28 23:10:28 25 4
gpt4 key购买 nike

比较 std::string 的最佳方法是什么?显而易见的方法是使用 if/else:

std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
// do something.
}

else if ( input == "blahblah" )
{
// do something else.
}

else if ( input == "blah" )
{
// do something else yet.
}

// etc. etc. etc.

另一种可能性是使用 std::mapswitch/case。进行大量(例如 8、10、12 次以上)这些比较时,最好的方法是什么?

最佳答案

这是一个使用 std::map 的示例。

#include <map>
#include <string>
#include <iostream>
#include <utility>

void first()
{
std::cout << "first\n";
}

void second()
{
std::cout << "second\n";
}

void third()
{
std::cout << "third\n";
}


int main()
{
typedef void(*StringFunc)();
std::map<std::string, StringFunc> stringToFuncMap;

stringToFuncMap.insert(std::make_pair("blah", &first));
stringToFuncMap.insert(std::make_pair("blahblah", &second));
stringToFuncMap.insert(std::make_pair("blahblahblah", &third));

stringToFuncMap["blahblah"]();
stringToFuncMap["blahblahblah"]();
stringToFuncMap["blah"]();
}

输出是:

second
third
first

这种方法的好处是:

  • 它易于扩展。
  • 它迫使您将字符串处理例程分解为单独的函数(有意编程)。
  • 函数查找是 O(log n),而您的示例是 O(n)

考虑使用 boost::function 使语法更好一些,尤其是类成员函数。

关于c++ - 比较 std::strings 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4772325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com