for_each not returning (boolean) value - c++

I have a program to verify if an IPv4 address entered as string is in valid dotted-quad notation.
The problem I am facing is that I'm not able to return (exit) function once I detect error. As per cppreference documentation for_each returns UnaryFunction. I tried using any_of and all_of but they require me using an loop (range-based loop) inside my lambda function which I'm trying to avoid. Am I missing something or it is not possible to return value in 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;

from for_each:
If f returns a result, the result is ignored.
i.e. there is no point in returning a value from your for_each lambda.
A good choice here is all_of, which accepts a UnaryPredicate rather than a UnaryFunction, since you want to make sure that all of the parts of the string pass the lambda successfully:
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;
});
all_of will stop iterating once an invalid part is found.

Am I missing something or it is not possible to return value in for_each.
for_each does return the UnaryFunction. But if you put a unary function to if expression, its meaningless.
In your case, a lambda without capturing can implicitly convert to a function pointer. A non-null function pointer as a boolean value is always true. Thus your
if(not for_each( /* ... */ ))
will be evaluated to false all the time.
As commentators and other answerers have already written, std::all_of is what you want here.

You shouldn't use for_each anyway. Replace it by the ranged-based for and it all becomes so much simpler and elegant. Put it all in a function and there you go:
auto is_ip_valid(const std::vector<std::string>& ipExplode)
{
for (auto&& str : ipExplode)
{
// ...
}
}

Related

std::unordered_map::count is not working in my code

I have a doubt with the solution of this question which is stated below -
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Strings["aa", "ab"] should return false and strings["aa", "aab"] should return true according to question.
Here is the code which I have attempted in the first place and I'm not getting a required output as mentioned above.
unordered_map<char,int>umap;
for(char m:magazine)
{
umap[m]++;
}
for(char r:ransomNote)
{
if(umap.count(r)<=1)
{
return false;
}
else{
umap[r]--;
}
}
return true;
}
In the above code, I have used umap.count(r)<=1 to return false if there is no key present.
For the strings ["aa","aab"], it is returning true but for strings ["aa","ab"], it is also returning true but it should return false.
Then I used another way to solve this problem by using just umap[r]<=0 in the place of umap.count(r)<=1 and it is working just fine and else all code is same.
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int>umap;
for(char m:magazine)
{
umap[m]++;
}
for(char r:ransomNote)
{
if(umap[r]<=0)
{
return false;
}
else{
umap[r]--;
}
}
return true;
}
I'm not able to get what i'm missing in the if condition of first code. Can anyone help me to state what I'm doing wrong in first code. Any help is appreciated.
unordered_map::count returns the number of items with specified key.
As you don't use multi_map version, you only have 0 or 1.
Associated value doesn't change presence of key in map.
To use count, you should remove key when value reaches 0:
for (char r : ransomNote) {
if (umap.count(r) == 0) {
return false;
} else {
if (--umap[r] == 0) {
umap.erase(r);
}
}
}
return true;

Iterating over vector of custom object with two conditions

Using C++11, I'd like to iterate over a vector and return a type that indicates that the index was not found.
I am use to the traditional for(;;) loop and specifying the index manually, as my code shows below.
inline std::size_t ItemList::FindItem(Items& Item)
{
for (std::size_t i = 0; i < ItemVector.size(); i++)
{
if (ItemVector[i]->GetId() == Item.GetId() && !ItemVector[i]->GetName().compare(Item.GetName()))
{
return i + 1;
}
}
return 0;
}
I'm also having to increment the index +1 in order to return a value of 0 (to accommodate unsigned size_t) to indicate the calling method that the index was not found (I understand this is asinine). I am assuming it would be more suitable to return something more like std::end()?
Would using a C++11 iterator approach be more efficient? The vector will populate to a large number and the find needs to be quick.
You could use std::find_if and work with iterators:
auto it = std::find_if(ItemVector.begin(), ItemVector.end(),
[&Item](Items *value) {
return value->GetId() == Item.GetId() && !value->GetName().compare(Item.GetName());
}
);
Then you can simply test if it != ItemVector.end() to know if you found something.
There will likely be no (or very small) difference between this and your version in term of speed, but it is a cleaner way to check if something was found or not.
Yes, an iterator would be the way to do this, you're actually writing your own version of find_if You could instead do:
find_if(cbegin(ItemVector), cend(ItemVector), [&](const auto& i){ return i.GetId() == Item.GetId() && i.GetName() != Item.GetName(); })
You can test whether the result of this function was found by testing for equality with cend(ItemVector).
Additionally if you need to find the index of the item you can pass this result after cbegin(ItemVector) to: distance
Live Example
My solution for double search condition that Lambda has multiple parameters in find_if
bool check_second_loop(FullFrame *image_track, guint64 object_id, bool *deletion)
{
auto itr= std::find_if(image_track->track_ids.begin(),
image_track->track_ids.end(),
[object_id](const guint64& a)
{
return a == object_id;
});
if (itr != image_track->track_ids.end())
{
image_track->track_ids.erase(itr);
if(image_track->track_ids.size()==0)
{
*deletion = true;
}
return true;
}
else
return false;
}
bool check_first_loop(guint64 object_id, gint source_id)
{
bool deletion = false;
auto it = find_if(full_frame_list.begin(), full_frame_list.end(),
[object_id, &deletion, source_id](FullFrame &x)
{
return check_second_loop(&x, object_id, &deletion)
&& x.camera_number == source_id;
});
if (it != full_frame_list.end())
{
// Found
return true;
}
else
return false;
}

C++ How to use less conditional statements?

For my assignment, I'm storing user login infos. I'm taking in a string which is the command. The command can be create, login, remove, etc. There are 10 total options, i.e 10 different strings possible. Can anyone explain a more efficient way to write this instead of 10 if and else if statements? Basically how should I format/structure things besides using a bunch of if (string == "one"), else if (string == "two"). Thank you
I expect that your lecturer would like you to extract function to another re-usable function:
string action;
command = CreateAction(action);
command.Do(...);
Ofcourse, inside you CreateAction class you still need to have the conditionals that determine which commands need to be created.
AbstractCommand CreateAction(action)
{
if (action == "login")
return LoginCommand();
else if (action == "remove")
return RemoveCommand();
..... etc etc
}
And if you really want to get rid of all the conditionals than you can create some self-registering commands but that involves a lot more code and classes......
You should look up things like Command Pattern and Factory Pattern
You can use function pointers and a lookup table.
typedef void (*Function_Pointer)(void);
void Create(void);
void Login(void);
void Remove(void);
struct Function_Option_Entry
{
const char * option_text;
Function_Pointer p_function;
};
Function_Option_Entry option_table[] =
{
{"one", Create},
{"two", Login},
{"three", Remove},
};
const unsigned int option_table_size =
sizeof(option_table) / sizeof(option_table[0]);
//...
std::string option_text;
//...
for (i = 0; i < option_table_size; ++i)
{
if (option_text == option_table[i].option_text)
{
option_table[i].p_function();
break;
}
}
Use a switch, and a simple hash-function.
You need to use a hash-function, because C and C++ only allow switching on integral values.
template<size_t N> constexpr char myhash(const char &x[N]) { return x[0] ^ (x[1]+63); }
char myhash(const string& x) { return x.size() ? x[0] ^ (x[1]+63) : 0; }
switch(myhash(s)) {
case myhash("one"):
if(s != "one") goto nomatch;
// do things
break;
case myhash("two"):
if(s != "two") goto nomatch;
// do things
break;
default:
nomatch:
// No match
}
Slight adjustments are needed if you are not using std::string.
I would recommend you to create a function for every specific string. For example, if you receive a string "create" you will call function doCreate(), if you receive a string "login" then you call function doLogin()
The only restriction on these function is that all of them must have the same signature. In an example above it was smh like this:
typedef void (*func_t) ();
The idea is to create a std::map from strings to these functions. So you wouldn't have to write 10 if's or so because you will be able to simple choose the right function from the map by the name of a specific string name. Let me explain it by the means of a small example:
typedef void (*func_t) ();
void doCreate()
{
std::cout << "Create function called!\n";
}
void doLogin()
{
std::cout << "Login function called!\n";
}
std::map<std::string, func_t> functionMap;
void initMap()
{
functionMap["create"] = doCreate;
functionMap["login"] = doLogin;
}
int main()
{
initMap();
std::string str = "login";
functionMap[str](); // will call doLogin()
str = "create";
functionMap[str](); // will call doCreate()
std::string userStr;
// let's now assume that we also can receive a string not from our set of functions
std::cin >> userStr;
if (functionMap.count(userStr))
{
functionMap[str](); // now we call doCreate() or doLogin()
}
else
{
std::cout << "Unknown command\n";
}
return 0;
}
I hope it will help you in someway=)
You can use a map which does the comparison for you.
Something like this:
Initialise map:
std::map<std::string, std::function<void(std::string&)>> map;
map["login"] = std::bind(&Class::DoLogin, this, std::placeholders::_1);
map["create"] = std::bind(&Class::DoCreate, this, std::placeholders::_1);
Receive message:
map.at(rx.msg_type)(rx.msg_data);
Handler:
void Class::DoLogin(const std::string& data)
{
// do login
}
Maybe you can create a std::map<std::string, int> and use map lookups to get the code of the command that was passed - you can later switch on that number. Or create an enum Command and have a std::map<std::string, Command> and use the switch.
Example:
enum Command
{
CREATE,
LOGIN,
...
};
std::map<std::string, Command> commandNameToCode;
// fill the map with appropriate values
commandNameToCode["create"] = Command::CREATE;
// somehow get command name from user and store in the below variable (not shown)
std::string input;
// check if the command is in the map and if so, act accordingly
if(commandNameToCode.find(input) != commandNameToCode.end())
{
switch(commandNameToCode[input])
{
case CREATE:
// handle create
break;
...
}
}

Making the code cleaner [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Sorry if this question is not suited for SO.
I have a C++ function that approximately looks like MyFun() given below.
From this function I am calling some(say around 30) other functions that returns a boolean variable (true means success and false means failure). If any of these functions returns false, I have to return false from MyFun() too. Also, I am not supposed to exit immediately (without calling the remaining functions) if an intermediate function call fails.
Currently I am doing this as given below, but feel like there could be a more neat/concise way to handle this. Any suggestion is appreciated.
Many Thanks.
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
I would replace each if statement with a more coincise bitwise AND assignment:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
Result &= AnotherFn1(); // Another fn that returns false on failure
Result &= AnotherFn2(); // Another fn that returns false on failure
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
Use something like a std::vector of std::function. It is a lot more maintenable.
Example: http://ideone.com/0voxRl
// List all the function you want to evaluate
std::vector<std::function<bool()>> functions = {
my_func1,
my_func2,
my_func3,
my_func4
};
// Evaluate all the function returning the number of function that did fail.
unsigned long failure =
std::count_if(functions.begin(), functions.end(),
[](const std::function<bool()>& function) { return !function(); });
If you want to stop when a function fail, you just have to use std::all_of instead of std::count_if. You dissociate the control flow from the function list and that is, in my opinion, a good thing.
You can improve this by using a map of function with name as key that will allows you to output which function failed:
std::map<std::string, std::function<bool()>> function_map;
bool MyFun() // fn that returns false on failure
{
bool Result = true;
// if need to call every function, despite of the Result of the previous
Result = AnotherFn1() && Result;
Result = AnotherFn2() && Result;
// if need to avoid calling any other function after some failure
Result = Result && AnotherFn1();
Result = Result && AnotherFn2();
return Result;
}
Instead of
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
begin to use booleans as what they are, truth values:
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn3()) // Another fn that returns false on failure
{
Result = false;
}
Then, all those conditions have the same code; they are basically part of one big condition:
if ( !AnotherFn1()
| !AnotherFn2()
| !AnotherFn3())
{
Result = false;
}
For your specific problem, where you want all functions be called, even if you know early you'll return false, it is important to not use the short circuiting operators && and ||. Using the eager bitwise operators | and & is really a hack, because they are bitwise and not boolean (and thus hide intent), but work in your situation iff AnotherFn? return strict bools.
You can negate what you do inside; less negations yield better code:
Result = false;
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
Result = true;
}
and then you can rid these assignments and instead return straightly:
if ( AnotherFn1()
& AnotherFn2()
& AnotherFn3())
{
return true;
}
cout << "something bad happened";
return false;
Summary
Old:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}
New:
bool MyFun() // fn that returns false on failure
{
if (AnotherFn1() &
AnotherFn2() &
AnotherFn3())
{
return true;
}
cout << "Some function call failed";
return false;
}
There are more possible improvements, e.g. using exceptions instead of error codes, but don't be tempted to handle "expections" instead.
! can be used as a cleaner alternative to false
Like this:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (!AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (!AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (!Result)
{
cout << "Some function call failed";
}
return Result;
}
how about using exceptions to handle failure:a neat exemple
the main question is, are the function call interdependant or not? can some be skipped if a previous one failed? ...

return std::unique_ptr containing std::map

I have a map of maps as follows:
std::map<char,std::map<short,char>> my_maps;
and I need to return a refrence to one of the maps corresponding to an specified key from a function.
I do not know how I should do this ,here is my code:
bool GetMap(char key,std::unique_ptr<std::map<short,char>> my_map){
auto m=my_maps.find(key);
if(m!=my_maps.end()){
my_map=m->second;
// I have also tried this: my_map=my_maps[_commandcode];
return(true);
}
return (false);
}
This is what I will do instead:
std::map<short,char>& GetMap(char key, std::map<char,std::map<short,char>> &my_maps)
{
auto m = my_maps.find(key);
if (m != my_maps.end())
{
return m->second;
}
throw std::exception("not found");
}