You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何在struct vector中匹配输入字符串 解决重复提示未找到问题

C++代码问题修正方案

原代码的问题在于将未匹配判断放在了遍历循环内部,每遍历到一个不匹配的条目就会触发一次「Article not found」输出,不符合需求。

核心实现逻辑

  • 新增matched_count整型变量,初始值为0,用于统计匹配到的条目数量
  • 遍历过程中仅处理匹配成功的条目:输出条目信息同时将matched_count加1,不匹配条目直接跳过
  • 全量遍历结束后,判断matched_count是否为0,仅为0时输出一次「Article not found」

修改后完整GiveName函数代码

void GiveName(vector <Article> vArticle)
{
    vector <Article> vInput;
    cout << "List of articles: " << endl;
    for (int i = 0; i < vArticle.size(); i++)
    {
        cout << vArticle[i].Id << ",  " << vArticle[i].name << ",  " << vArticle[i].desc << ",  " << vArticle[i].price << endl;
    }
    cout << "\n\n\n";
    cout << "Enter an article name" << endl;
    string input;
    cin >> input;
    // 记录匹配条目数
    int matched_count = 0;
    for (int i = 0; i < vArticle.size(); i++)
    {
        if (vArticle[i].name == input)
        {
            cout << vArticle[i].Id << ",  " << vArticle[i].name << ",  " << vArticle[i].desc << ",  " << vArticle[i].price << endl;
            matched_count++;
        }
    }
    // 全量遍历后统一判断是否无匹配
    if (matched_count == 0)
    {
        cout << "Article not found" << endl;
    }
}

可选性能优化

如果数据量较大,可以将函数入参改为常量引用const vector<Article>& vArticle,避免整个vector拷贝带来的额外性能开销。

内容的提问来源于stack exchange,提问作者Sodium Chloride121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:15:04