Sum*_*jkl 9 c++ string if-statement input cin
我是新来的C++.我在python中有过一些经验,发现"如果a in b"真的很容易,我想知道C++中是否有相同的东西.
背景
我一直在尝试创建一个字符串列表,并检查输入是否在该列表中.我想这样做的原因是因为我想只使用一个函数,如果输入实际上在该函数中做了一些事情.(在这种情况下更改int x和y坐标)
题
string myinput;
string mylist[]={"a", "b", "c"};
cin>>myinput;
//if myinput is included in mylist
//do other stuff here
Run Code Online (Sandbox Code Playgroud)
如何检查if
输入myinput
是否包含在字符串中mylist
?
Jer*_*fin 13
你可以使用std::find
:
std::string myinput;
std::vector<std::string> mylist{"a", "b", "c"};
std::cin >> myinput;
if (std::find(std::begin(mylist), std::end(mylist), myinput) != std::end(mylist))
// myinput is included in mylist.
Run Code Online (Sandbox Code Playgroud)
只使用三个字符串就可以正常工作,但是如果你有更多的字符串,那么你可能会更好std::set
或者更好std::unordered_set
.
std::set<std::string> myset;
// put "a", "b", and "c" into the set here
std::cin >> myinput;
if (myset.find(myinput) != myset.end())
// myinput is included in myset.
Run Code Online (Sandbox Code Playgroud)
使用std::find
:
std::size_t listsize = sizeof mylist / sizeof mylist[0];
if (std::find(mylist, mylist + listsize, myinput) != mylist + listsize) {
//found
}
Run Code Online (Sandbox Code Playgroud)
如果您事先知道列表的大小,我建议std::array
它公开迭代器和size()
函数,以及相对于内置数组的一些其他好处。请注意,这仅适用于 C++11(C++03 几乎等效为std::vector
),并且 C++11 也带有std::begin
和std::end
,这将其简化为:
if (std::find(std::begin(mylist), std::end(mylist), myinput) != std::end(mylist))
Run Code Online (Sandbox Code Playgroud)
在 C++03 中创建自己的内置数组也相当容易,但是对于公开begin()
和end()
成员的标准容器,这应该不是太必要,尽管它更通用。