How can you say that all std :: vector <std :: string> is a given size in single line space?

I have a method that accepts std :: vector sha1 hashes as strings whose length should be exactly 20 characters. It would be great to say in one layer that this assumption is being met.

void MyClass::setSha1Sums(const std::vector<std::string>& sha1Sums)
{
  assert(magic_oneliner_which_verifies_that_all_strings_are_20_chars_long);
  sha1Sums_ = sha1Sums;
}
+3
source share
5 answers

C ++ 03, with boost (> = 1.33):

std::find_if( sha1Sums.begin(), sha1Sums.end()
            , boost::bind( &std::string::size, _1 ) != 20U
                ) == sha1Sums.end();

Note that it !=is an overloaded operator that increases supplies to create more complex bundles that make basic relational and logical operators easier to use.

http://www.boost.org/doc/libs/1_45_0/libs/bind/bind.html#operators

+5
source

I would use std::adjacent_find:

bool same_lengths = 
    std::adjacent_find(v.begin(), v.end(), [](std::string a, std::string b) 
    {
        return a.length() != b.length(); 
    }) == v.end();

, . , .

+3

std::all_of() true, .

bool result = std::all_of(sha1Sums.begin(), sha1Sums.end(), [](std::string &s)
{
    return s.length() == 20;
});
+2
source

You will need a "for each" function that returns true or false based on the transmitted vector. You can then pass this function to your string vector in an assert statement.

+1
source

Not one liner, but I find it closer to the clearest solution in current C ++ (instead of std :: all_of with a lambda or foreach loop in 0x):

void MyClass::setSha1Sums(std::vector<std::string> const &sha1Sums) {
  sha1Sums_.clear();
  BOOST_FOREACH(string const &x, sha1Sums) {
    assert(x.size() == 20);
    sha1Sums_.push_back(x);
  }
}

This also has a slight advantage in that you can easily find (for example, a log) an offensive line to fix the problem if / when it occurs.

+1
source

Source: https://habr.com/ru/post/1790571/


All Articles