Search code examples
c++c++17stdvector

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


i have vector

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

i don't want to go with the loop rout

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

is there any more elegant way to check if all elements in the vector start with "-" ? can use c++17


Solution

  • You can use 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) == '-'; });
    

    This will work in C++11 and newer.