c++ 需要帮助在向量中查找单词

kx1ctssn  于 2023-05-02  发布在  其他
关注(0)|答案(2)|浏览(99)

我有两个向量:ab。我想检查b中的一个单词是否可以在a中找到。

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    vector<string> a = {"abcd", "efgh","ijkl"};
    vector<string> b = {"efg","mno"};

    for(int j = 0; j < b.size(); ++j) {
        if (find(a.begin(), a.end(), b[j]) != a.end()) {
            cout << b[j] << endl;
        }
    }  

    return 0;
}

我试着这样做:通过向量a进行循环,并将元素彼此进行比较。我期望输出"efg",但它什么也不打印。
这是什么原因呢?

xdnvmnnf

xdnvmnnf1#

我试着这样做:made循环通过向量a并将元素彼此进行比较。
你的想法很好,但你的方法需要一些调整。std::find()查找 exact 匹配,但"efg"a中不作为一个完整的元素存在。您需要执行 partial 匹配,因为"efg"a"efgh"元素的 * 子字符串 *。
你可以使用std::find_if()代替,使用std::string::find()进行子字符串搜索,例如:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    vector<string> a = {"abcd", "efgh", "ijkl"};
    vector<string> b = {"efg", "mno"};

    for(const string& substr : b){
        auto findSubStr = [&](const string &elem){
            return elem.find(substr) != string::npos;
        };
        auto iter = find_if(a.begin(), a.end(), findSubStr);
        if (iter != a.end()) {
            cout << "found " << substr << " in " << *iter << endl;
        } else {
            cout << "did not find " << substr << endl;
        }
    }

    return 0;
}

Online Demo

bjp0bcyl

bjp0bcyl2#

你所做的所有比较(显式地或使用std::find)都将比较整个字符串。你需要找到 substrings
你可以循环遍历a向量,然后遍历b向量,并检查b中的每个元素是否可以在a的元素中找到:

for (auto const& a_string : a)
{
    for (auto const& b_string : b)
    {
        if (a_string.find(b_string) != std::string::npos)
        {
            // b_string found inside of a_string
        }
    }
}

相关问题