C++17 使用 lambda 无循环检查向量中的所有元素是否以子字符串开头

C++17 Check if all elements in vector start with substring using lambda no loop

我有向量

std::vector<std::string> v = {"--d","--e","--f"};

我不想循环失败

for (auto it = v.begin(); it != v.end(); ++it){
    ...
}

有没有更优雅的方法来检查向量中的所有元素是否以“-”开头? 可以使用c++17

您可以使用 std::all_of:

#include <algorithm>

bool startWithDash = std::all_of(v.begin(), v.end(),
  [](std::string const & e) { return not e.empty() and e.at(0) == '-'; });

这将适用于 C++11 和更新版本。

使用C++17,可以使用std::string_view:

auto is_option = std::all_of(cbegin(v), cend(v),
  [](std::string_view sv) { return sv.substr(0,1) == "-"; });

在 C++20 中,甚至会有 string_view::starts_with 并且可以在 lambda 中使用 sv.starts_with("-")

怎么样:

#include <algorithm>

bool allBeginWithMinus = std::all_of(v.begin(), v.end(), [v](std::string& str)->bool
return (!str.empty() && ("-" == str.front()))});