查找数组的最佳方法包含给定字符串

时间:2014-12-14 06:36:47

标签: c++ arrays string performance classification

我有一些字符串数组和一个函数,它获取一个字符串并返回它的类型(字符串所属的数组)

我怎样才能以最快的速度做到这一点?

string arr1[] = {"a", "b", "c"};
string arr2[] = {"d", "e", "f"};
string arr3[] = {"g", "h", "i"};
string arr4[] = {"j", "k", "l"};

...
string getFamily(string input)
{
if(arr1.contains(input)
return "TYPE_1";
...
}

由于

1 个答案:

答案 0 :(得分:0)

这不是很优雅,但是如果你想要快速,你可以制作一个准备好的unordered_map来进行搜索,如果这个函数被调用100次会很有用(如果很少调用则会浪费)。理想情况下,您可以在类对象而不是全局变量中创建此容器,并且返回类型是整数值而不是字符串。这将产生对O(1)的搜索,其中成本在密钥的散列中。但我不太了解你的要求。

如果你宁愿打电话一次,那就按照Joachim Pileborg的建议去做一系列std :: find电话直到你受到打击。

#include <iostream>
#include <unordered_map>
#include <string>

std::unordered_map< std::string, std::string > g_map;

std::string arr1[] = {"a", "b", "c"};
std::string arr2[] = {"d", "e", "f"};
std::string arr3[] = {"g", "h", "i"};
std::string arr4[] = {"j", "k", "l"};

const char * map_value( const std::string & input )
{
    std::unordered_map< std::string, std::string >::iterator iter( g_map.find( input ) );
    return iter == g_map.end() ? "NOT FOUND" : iter->second.c_str();
}

int main( int argc, char ** argv )
{
    // Build the map;
    for( int i = 0; i < sizeof( arr1 ) / sizeof( std::string ); ++i )
        g_map[arr1[i]] = "TYPE_1";
    for( int i = 0; i < sizeof( arr2 ) / sizeof( std::string ); ++i )
        g_map[arr2[i]] = "TYPE_2";
    for( int i = 0; i < sizeof( arr3 ) / sizeof( std::string ); ++i )
        g_map[arr3[i]] = "TYPE_3";
    for( int i = 0; i < sizeof( arr4 ) / sizeof( std::string ); ++i )
        g_map[arr4[i]] = "TYPE_4";

    std::string input;
    std::cout << map_value( "b" ) << std::endl;
    std::cout << map_value( "z" ) << std::endl;
    std::cout << map_value( "eb" ) << std::endl;
    std::cout << map_value( "j" ) << std::endl;
    std::cout << map_value( "f" ) << std::endl;
    return 0;
}

输出:

TYPE_1
NOT FOUND
NOT FOUND
TYPE_4
TYPE_2