ToLower std :: vector <std :: string>

时间:2018-03-21 17:25:28

标签: c++ string vector tolower

这与问题有关:

String array to C++ function

虽然现在一切正常,但我唯一无法完成的是 tolower 用户输入,因为我收到错误:

功能

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 转换为字符串,以便我可以将该单词转换为小写?

2 个答案:

答案 0 :(得分:7)

这是因为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) {

答案 1 :(得分:1)

std::transform需要能够更改第三个参数解引用的内容。

由于termconst对象,因此不适用于您的情况。

您可以创建函数本地对象来存储转换后的字符串。

std::string lowercaseTerm(term);
transform(term.begin(), term.end(), lowercaseTerm.begin(), ::tolower);

然后在以下行中使用lowercaseTerm

  if (possible_name.compare(lowercaseTerm) == 0)