I'm new here and to C++. I've had some experience in python, and found "if a in b" really easy, and I'm wondering if there's an equivalent in C++.
Background
I've been trying to make a list of strings and check if an input is in that list. The reason I want to do this is because I want to only use a function if the input will actually do something in that function. (Change int x and y coordinates in this case)
Question
string myinput;
string mylist[]={"a", "b", "c"};
cin>>myinput;
//if myinput is included in mylist
//do other stuff here
How do I check using an if
whether the input myinput
is included in string mylist
?
You could use 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.
This works fine with only three strings, but if you're going to have many more, you'd probably be better off with an std::set
or std::unordered_set
instead.
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.