这与问题有关:

String array to C++ function

尽管现在一切正常,但我无法完成的唯一操作是将降低到用户输入的,因为我遇到了错误:

功能

bool lookupTerm(const std::string& term, const std::vector<std::string>& possible_names) {

    transform(term.begin(), term.end(), term.begin(), ::tolower);
    for (const std::string &possible_name : possible_names)
    {
        if (possible_name.compare(term) == 0)
            return true;
    }
    return false;
}

参量
const std::vector<std::string> possible_asterisk         = { "star" ,
                                                              "asterisk" ,
                                                              "tilde"};
string term = "SoMeWorD";

错误
 In file included from /usr/include/c++/7.2.0/algorithm:62:0,
                 from jdoodle.cpp:5:
/usr/include/c++/7.2.0/bits/stl_algo.h: In instantiation of '_OIter std::transform(_IIter, _IIter, _OIter, _UnaryOperation) [with _IIter = __gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> >; _OIter = __gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> >; _UnaryOperation = int (*)(int) throw ()]':
jdoodle.cpp:40:64:   required from here
/usr/include/c++/7.2.0/bits/stl_algo.h:4306:12: error: assignment of read-only location '__result.__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> >::operator*()'
  *__result = __unary_op(*__first);

我知道转换应该接收一个字符串。如何立即将 std::vector 转换为简单的字符串,以便将该单词转换为小写?

最佳答案

这是因为termconst引用。在将其转换为小写字母之前进行复制:

bool lookupTerm(const std::string& term, const std::vector<std::string>& possible_names) {
    std::string lower(term);
    transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
    for (const std::string &possible_name : possible_names)
    {
        if (possible_name.compare(lower) == 0)
            return true;
    }
    return false;
}

您还可以通过删除const并按值获取参数来达到相同的效果:
bool lookupTerm(std::string term, const std::vector<std::string>& possible_names) {

10-08 16:55