【问题标题】:How to find a certain value in a vector of strings如何在字符串向量中找到某个值
【发布时间】:2019-11-06 18:29:36
【问题描述】:

我正在尝试为分配创建一个程序,该程序将从字符串向量中添加和删除字符串,但首先我需要创建一个函数来查找该字符串是否已存在于向量中。

我已经尝试使用循环来搜索向量以在每个索引处找到特定的所需字符串。我尝试添加一个break;退出,如果该字符串被发现。我不知道该函数应该是无效或布尔值。 P>

bool FindString(int vctrSize, vector<string> restaurantVctr, string targetRestnt) {
    int i;

    for (i = 0; i < vctrSize; ++i) {
        if (restaurantVctr.at(i) == targetRestnt) {
            return true;
            break;
        }
        else {
            return false;
        }
    }
}

如果找到字符串,我希望输出为真,否则显然为假。

编辑:我忘了提到我还收到了警告:“并非所有控制路径都返回值”

【问题讨论】:

  • 这有什么错std::find? SPAN>
  • return false;应该是环路的外部。跨度>
  • 其他建议:1) 不要传递大小,因为std::vector 已经知道了。 2)通过传递const &amp;载体能够避免作出复制不必要。 3)路过const &amp;字符串出于同样的原因。 4)如果你使用std::findstd::binary_search(必须排序才能使用那个),你根本不需要单独的函数。

标签: c++ visual-studio vector visual-c++


【解决方案1】:

您应该尽可能使用标准算法:

auto result = std::find(restaurantVctr.begin(), restaurantVctr.end(), targetRestnt);
return result != restaurantVctr.end();

这正是std::find 的用途。

【讨论】:

  • 没错。此外,如果向量恰好是排序的,std::binary_search 在这里是理想的,具有更好的复杂性。
【解决方案2】:

虽然我建议像其他人推荐的那样使用std::find,但如果您对自己的代码有什么问题感到好奇,那么问题出在您的else

for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        break;
    }
    else {
        return false;
    }
}

如果你的向量中的第一项等于targetRestnt,那么你的函数返回——也就是说,它结束执行。

如果它不在整个列表中,您只想返回 false ——也就是说,您希望执行整个循环:

for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        // Also, you don't need a break here: you can remove it completely
        // For now, I just commented it out
        // break;
    }
}

// We didn't find it:
return false;

【讨论】:

  • break(也出现在 OP 的代码中)是多余且无法访问的,因为 return 将首先退出该函数。
  • @foreknownas_463035818 我认为它不会在这里造成问题,因为return 将始终在break 之前执行,但我将其编辑了,因为你们俩都是对的:它是不需要的。
猜你喜欢
  • 1970-01-01
  • 2021-12-31
  • 2020-03-19
  • 2013-06-12
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多