for_each没有返回(布尔值)值

Dar*_*row 6 c++ c++11

我有一个程序来验证作为字符串输入的IPv4地址是否是有效的点分四位表示法.

我面临的问题是,一旦检测到错误,我就无法返回(退出)功能.根据cppreference文档for_each返回UnaryFunction.我尝试使用any_of和all_of,但是他们要求我在我的lambda函数中使用一个循环(基于范围的循环),我试图避免.我错过了什么或者无法在for_each中返回值.

vector<string> ipExplode;
string ip;
bool    inValidIp = false;
cout << "Server IP : ";
cin >> ip;
trim(ip);
ipExplode = explode(ip, '.');
if(not for_each(ipExplode.begin(), ipExplode.end(), [](const string& str) -> bool{
    int32_t ipNum;
    if(regex_search(str, regex("\\D+")))
        return false;
    try
    {
        ipNum = stoi(str);
        if(ipNum < 0 or ipNum > 255)
            return false;
    }
    catch (std::exception& ex)
    {
        return false;
    }
}))
    return false;
Run Code Online (Sandbox Code Playgroud)

Rot*_*tem 8

来自for_each:

如果f返回结果,则忽略结果.

即从for_eachlambda 返回一个值是没有意义的.

这里一个很好的选择是all_of,它接受一个UnaryPredicate而不是一个UnaryFunction,因为你想确保字符串的所有部分成功传递lambda:

bool isValid = std::all_of(ipExplode.begin(), ipExplode.end(), [](const std::string& str) -> bool{
    if(regex_search(str, regex("\\D+")))
        return false;
    try
    {
        int32_t ipNum = stoi(str);
        if(ipNum < 0 or ipNum > 255)
            return false;
    }
    catch (std::exception& ex)
    {
        return false;
    }
    return true;
});
Run Code Online (Sandbox Code Playgroud)

all_of 一旦找到无效部分,将停止迭代.