-1

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

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
user63898
  • 29,839
  • 85
  • 272
  • 514

3 Answers3

1

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.

AVH
  • 11,349
  • 4
  • 34
  • 43
  • thanks "not" will not be valid in older VS IDE's better use standart – user63898 Feb 04 '21 at 15:23
  • @user63898 `not` is definitely standard, see [alternative operators](https://en.cppreference.com/w/cpp/language/operator_alternative). If it doesn't work in old VS versions, it's because they are famously very buggy and don't follow the standard by default. E.g. see [Why does VS not define the alternative tokens for logical operators?](https://stackoverflow.com/questions/24414124/why-does-vs-not-define-the-alternative-tokens-for-logical-operators) for more info about this particular issue. – AVH Feb 04 '21 at 16:18
  • Oh, btw, I like using `not`, `and`, etc. because it makes the code more readable in my opinion. It reads more like plain English. – AVH Feb 04 '21 at 16:19
  • c++ is not python , and there are compilers that not understand it – user63898 Feb 04 '21 at 20:11
  • @user63898 Yes, and those compilers are not standard compliant. In the case of MSVC, you can make it understand by telling it it needs to be standard compliant (using the `/Za` flag). Please read the pages I linked, this is completely standard C++. – AVH Feb 05 '21 at 07:05
1

Using C++17, you can use std::string_view:

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

In C++20, there will even be string_view::starts_with and one could use sv.starts_with("-") inside the lambda.

n314159
  • 4,990
  • 1
  • 5
  • 20
1

How about:

#include <algorithm>

bool allBeginWithMinus = std::all_of(v.begin(), v.end(), [v](std::string& str)->bool
return (!str.empty() && ("-" == str.front()))});
  • @user63898 The `-> bool` part is not strictly necessary if the return type can be automatically deduced, which is the case here. – AVH Feb 04 '21 at 16:12
  • i know, its better to set it good hint for the compiler – user63898 Feb 04 '21 at 20:10