C ++ is equivalent to Python "if x in [string1, string2, ...]"

My mini-project is to make chatbot; I do not have open sources on Google, and I have not researched how to build them. I am trying to understand how well I understand C ++: Saying this,

I try to create a “box” that stores all the “questions” that can be asked, and seeing “if” that the “question” is in the “box”, it will execute the specified code.

In Python, this will be more or less:

Box = ["Yes", "YES", "yes", "yEs", "YeS", "yES"]

print "Will you be working today?"
response = raw_input("> ")
if response in Box:
    print "Very well, then how can I assist you?"

So how am I going to do this in C ++. Or what is it called in C ++? An array? List? Vector? This is a bit confusing to distinguish those in C ++.

+4
source share
5 answers

, :

#include <string>
#include <cctype>
#include <functional>
#include <algorithm>

// convert string to lowercase
std::string lower_case(std::string s)
{
    std::transform(s.begin(), s.end(), s.begin()
        , std::ptr_fun<int, int>(std::tolower));
    return s;
}

int main()
{
    std::string response;

    // ask question and get response

    // now you don't need to look at every combination
    if(lower_case(response) == "yes")
    {
        // positive response code
    }

    // etc...
}
+6

- , <string>, <vector> <algorithm>:

vector<string> box = { "yes"...};
//get input
if(std::find(box.begin(), box.end(), search_str) != box.end()) {
    //found
}
+3

, .

std::string downcased(std::string s) {
  std::locale loc{"en_US.UTF-8"};
  std::transform(begin(s), end(s), begin(s), [&](auto const& c) {
    return std::tolower(c, loc);
  });
  return s;
}

,

if(downcased(input_string) == "yes") ...

"" .

Boost, downcased():

if(boost::algorithm::to_lower_copy(input_string) == "yes") ...

, ++ C. Python, , , -. ++ std::vector<> . , , , . , algortithms, std::find(), . ,

std::vector<std::string> const ys = {"yes", "yEs", };  // &c
if(std::find(begin(ys), end(ys), "yeS") != end(ys))
  ...
+3

"" , std:: .

, : " X?" . std::vector, , .

#include <iostream>
#include <set>

int main()
{

    std::string input;

    std::cin >> input;

    std::set<std::string> box{"Yes", "YES", "yes", "yEs", "YeS", "yES"};

    if (box.find(input) != box.end())
    {
        std::cout << "Very well, then how can I assist you?" << std::endl;
    }
    return 0;

}
+2

, , ++ Python . Python list, , ++ . C-style , std::array, std::list std::vector - . std::vector .

, , , , , . Python set ++ 11 std::unordered_set ( -).

#include <iostream>
#include <string>
#include <unordered_set>

int main() {
  std::unordered_set<std::string> box = {"Yes", "YES", "yes"};
  std::string input;
  std::getline(std::cin, input);
  if(box.count(input)) {
    std::cout << "Very well, then how can I assist you?\n";
  }
}
+1

Source: https://habr.com/ru/post/1599606/


All Articles