【问题标题】:Find all words in container that start with a given character查找容器中以给定字符开头的所有单词
【发布时间】:2018-09-05 08:35:22
【问题描述】:

我需要帮助来搜索容器中的项目。

例如:我在一个容器中有以下单词:

crr.push_back("fred");
crr.push_back("barney");
crr.push_back("pavel");
crr.push_back("zoot");
crr.push_back("jim");
crr.push_back("peter");
crr.push_back("patrick");

我用它来寻找:

const bool Contains(vector<char*>& Vec, char* Element)
{
    if (find(Vec.begin(), Vec.end(), Element) != Vec.end())
        return true;

    return false;
}

int main()
{
    if (Contains(crr, "patrick"))
    {
        system("cls");
        printf("Found\n");
    }
    else
    {
       system("cls");
       printf("Nah\n");
    }
}

它支持Found,因为在容器中找到了"patrick",但我需要找到所有单词,例如,以'p' 开头的单词。例如,输出可能是:

pavel
peter
patrick

我怎么能意识到这一点?谢谢。

【问题讨论】:

    标签: c++ algorithm vector stl containers


    【解决方案1】:

    您可以将所有以'p' 开头的单词复制到std::vector&lt;std::string&gt; 容器中,然后显示其内容。这可以在线性时间运行中完成,即 O(n)。空间复杂度也是线性的,因为您需要一个专用向量来存储以'p' 开头的每个单词。

    您可以通过提供合适的谓词,使用函数模板std::copy_if 来实现这一点,例如以下lambda starts_with_p

    // returns true whether the string starts with 'p', false otherwise
    auto starts_with_p = [](std::string word) {
        if (word.front() == 'p')
            return true;
        return false;
    };
    

    现在,只需将std::copy_if 与该谓词一起使用:

    std::vector<std::string> matched_words;
    
    std::copy_if(crr.begin(), crr.end(), 
                 std::back_inserter(matched_words), starts_with_p);
    

    向量matched_words 包含原始容器中以'p' 开头的所有单词。您现在可以轻松地显示它们:

    for (const auto& word: matched_words)
        std::cout << word << std::endl;
    

    如果您不想要线性空间复杂度而是恒定的空间复杂度,即 O(1),并且您的容器 crr 支持随机访问迭代器,您可以先对集合进行排序 crr使用std::sort 函数模板并使用std::equal_range 对其执行二进制搜索,以获得所有以'p' 开头的单词的子范围:

    std::sort(crr.begin(), crr.end());
    
    auto cmp_1st_char = [](std::string a, std::string b) {
        return a.front() < b.front();
    };
    
    auto p = std::equal_range(crr.begin(), crr.end(), "p", cmp_1st_char);
    
    for (auto it = p.first; it != p.second; ++it)
        std::cout << *it << std::endl;
    

    但是请注意,排序的运行时间复杂度是 O(n log n)。因此,通过这两种选择,您将面临运行时间和空间复杂度之间的权衡。

    【讨论】:

    • 谢谢,我会试试这个。如果我输入两个或更多符号来精确搜索,它会起作用吗?
    • @JoeDonson 只需编写一个合适的谓词来表达您的排序标准。
    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 2013-08-29
    • 2020-03-15
    • 2011-02-22
    • 2013-03-09
    • 2022-11-17
    • 1970-01-01
    相关资源
    最近更新 更多