簡體   English   中英

Todower std :: vector <std::string>

[英]ToLower std::vector<std::string>

這與問題有關:

字符串數組到C ++函數

盡管一切都在現在的工作很好,我沒能做到的唯一事情是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轉換為簡單的字符串,以便將該單詞轉換為小寫?

這是因為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) {

std::transform需要能夠更改第三個參數取消引用的內容。

這對您不起作用,因為termconst對象。

您可以創建函數本地對象來存儲轉換后的字符串。

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

然后在下一行中使用lowercaseTerm

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM