[英]How to say if something is in something else c++
I was wondering if there is an easy way to write this if statement in c++. 我想知道是否有一种简单的方法可以在c ++中编写此if语句。
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. 没有语言上的直接支持,但是您可以使用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: 现在您可以使用初始化列表直接在if语句中使用此功能:
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:- 您可以使用std :: find函数搜索数组。假设您的数组为arr = [“ C”,“ X”,“ I”]:查找字符串c =“ C”例如,您的语句将更改为:-
if(find(arr.begin(),arr.end(),c)!=arr.end())
{
//found do something
}
There is no "in" in C++ C ++中没有“ in”
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::unordered_map
(C ++ 11哈希表)在性能方面要比通过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, ie avoiding iterators. std::set
和std::unordered_map
都具有一个count
函数,该函数使测试值看起来很干净,即避免使用迭代器。
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, eg g++ -std=c++11 main.cc
. 编译时不要忘记设置C ++ 11标准,例如g++ -std=c++11 main.cc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.