您如何断言所有 std::vector一行中是否有给定的尺寸?
我有一个方法,它接受 sha1 哈希值的 std::vector 作为字符串,长度必须恰好为 20 个字符。如果能用一句话断言这一先决条件得到尊重,那就太好了。
void MyClass::setSha1Sums(const std::vector<std::string>& sha1Sums)
{
assert(magic_oneliner_which_verifies_that_all_strings_are_20_chars_long);
sha1Sums_ = sha1Sums;
}
I have a method which accepts a std::vector of sha1 hashes as strings which must exactly 20 characters long. It would be great to assert in a one-liner that this precondition is respected..
void MyClass::setSha1Sums(const std::vector<std::string>& sha1Sums)
{
assert(magic_oneliner_which_verifies_that_all_strings_are_20_chars_long);
sha1Sums_ = sha1Sums;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C++03,带 boost (>= 1.33):
请注意,
!=
是一个重载运算符,boost 提供的功能可以使使用基本关系和逻辑运算符构建更复杂的绑定变得更简单。http://www.boost.org/doc/libs /1_45_0/libs/bind/bind.html#operators
C++03, with boost (>= 1.33):
Note that the
!=
is an overloaded operator that boost supplies to make building more complex binds which use basic relational and logical operators simpler.http://www.boost.org/doc/libs/1_45_0/libs/bind/bind.html#operators
我会使用 std::adjacent_find :
这会查找两个具有不同长度的连续元素。如果全部长度相同,则返回结束迭代器。
I would use
std::adjacent_find
:This looks for two consecutive elements that have different lengths. If all are the same length, it returns the end iterator.
如果范围内的每个元素都存在条件,则
std::all_of()
返回true
。std::all_of()
returnstrue
if the condition is present at every element of the range.您将需要一个“foreach”函数,该函数根据传递的向量返回 true 或 false。然后,您可以依次将该函数传递给断言语句中的字符串向量。
You will need a "for each" function that returns true or false based on the vector that is passed. You can then in turn pass that function to your vector of strings in your assert statement.
不是一个单行代码,但我发现这接近当前 C++ 中最清晰的解决方案(而不是 0x 中带有 lambda 或 foreach 循环的 std::all_of):
这也具有您可以轻松找到的轻微优势(例如 log ) 有问题的字符串,以便在问题发生时修复问题。
Not a one liner, but I find this close to the most clear solution in current C++ (instead of std::all_of with a lambda or a foreach loop in 0x):
This also has the slight advantage that you can easily find (e.g. log) the offending string to fix the problem if/when it occurs.