【问题标题】:ToLower std::vector<std::string>ToLower std::vector<std::string>
【发布时间】:2018-03-21 17:25:27
【问题描述】:

这与问题有关:

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 转换为简单的 string 以便我可以将该单词转换为小写?

【问题讨论】:

  • 不相关,但没有必要直接与 0 进行比较。0 是假的,所以可以使用 ! 运算符。
  • 发生错误是因为您试图修改const 对象。

标签: c++ string vector tolower


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    这不适用于您的情况,因为 termconst 对象。

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

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

    然后在下一行使用lowercaseTerm

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 2017-09-21
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多