I’m trying to check whether a string exists in an array in as little lines as possible example:
string foo[] = {blah,blahhh,blahhhh}
string bar = "blah";
if (bar in foo){
cout << "true";
}else {
cout << "false";
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is not this keyword nor this construct in C++.
You have to do a loop or use the find function.
http://www.cplusplus.com/reference/algorithm/find/
For other people that try to do the same thing (since is a question a lot of people asked to me in the past) : char arrays and string literals (that are const char arrays) cannot be compared with equality or with built-in operators : comparing two char literals is the same as comparing two pointers.
You can however use the std::string type or use old C style functions like strcmp.
If you really want to avoid writing too much lines of code just write another function with more lines and call it with one line. You then can put it in a nice header file and include it when you need 🙂
If you instead of an array have a pointer you should use a function where u can pass size as a parameter.
Now, if you array is really big, i don’t think you would like to use an O(n) linear search into an array, in that case I know you would prefer to use std::map or std::hash_map (note that hash_map is not available in all versions of the STL).
std::map uses internally a Red Black Tree (or an AVL tree, depending on the implementation), so lookup operation is O(log n) worst case, faster than O(n).
std::hash_map instead uses internally an hashtable, giving a worst case complexity O(n) but an average complexity of O(1), very fast in real world applications.