I was wondering if there is an easy way to write this if statement in c++.
string c="B";
if(c=="B"||c=="X"||c=="I")
{
//stuff
}
for example,
string c="B";
if(c in {"b","X","I"})
{
//stuff
}
I was wondering if there is an easy way to write this if statement in c++.
string c="B";
if(c=="B"||c=="X"||c=="I")
{
//stuff
}
for example,
string c="B";
if(c in {"b","X","I"})
{
//stuff
}
There is no direct support in language for this, but you can emulate it using function. For example, let us define a function that accept a string and a vector of strings to be compared:
bool in(const std::string& s, std::vector<std::string> v)
{
for (auto&& i : v)
if ( s == i)
return true;
return false;
}
now you can use this function directly in you if statement, using an initilizer list:
int main()
{
std::string c = "B";
if ( in(c, {"C","X","I", "B"}) )
std::cout << "found\n";
else
std::cout << "not found\n";
}
You can use the std:: find function to search your array.Suppose your array is arr=["C","X","I"] : tofind string c="C" For example your statement will change to:-
if(find(arr.begin(),arr.end(),c)!=arr.end())
{
//found do something
}
There is no "in" in C++
If doing multiple searches, std::set
or std::unordered_map
(C++11 hash table) will be better performance-wise than linear search through an array with std::find
.
std::set<std::string> data_set{"B","X","I"};
//...somewhere else
bool has_c = data_set.count(c)>0;
Both std::set
and std::unordered_map
have a count
function that makes testing for a value pretty clean looking, i.e. avoiding iterators.
Here's a full working program,
#include <string>
#include <set>
#include <iostream>
using namespace std;
int main()
{
set<string> data_set{"C","X","I"}
//...somewhere else
string c="B";
if( data_set.count(c)>0 )
{
cout << "here\n";
}
else
{
cout << "not\n";
}
}
Don't forget to set C++11 standard when you compile, e.g. g++ -std=c++11 main.cc
.