【问题标题】:How do you compare a string to a vector value?如何将字符串与向量值进行比较?
【发布时间】:2015-01-22 22:41:18
【问题描述】:

如何将 a 中的字符串与向量中的值进行比较<:string>?

我试了str,下面打印错误。

.....

    vector<std::string> dat;
    vector<std::string> pdat;
    dat = my();
    for(int b = 2; b < dat.size(); b+=7){
    //      cout << dat[b] << " " << endl;
            if(!strcmp(dat[b], "String\n"){    // The error is here
                    pdat.push_back(dat[b]);
            }
    }

my.cpp:在函数'std::vector > ngr()'中:
my.cpp:53:32:错误:无法将参数 '1' 转换为 '__gnu_cxx::__alloc_traits > >::value_type {aka std::basic_string}' 为 'const char*' 到 'int strcmp(const char*, const char*)'

【问题讨论】:

    标签: c++ string c++11 vector


    【解决方案1】:

    std::string 与普通的== 进行比较。这是因为 == 运算符被重载以对 std::strings 进行字符串比较。

    if (dat[b] == "String\n") {
    

    如果您正在处理 C++ 字符串,则不需要 string.h 中的任何 str* 函数,因此您最好根本不包含它。

    【讨论】:

      【解决方案2】:

      只需使用operator== 来比较std::string 和const char*:

      if(dat[b] == "String\n"){    //
          pdat.push_back(dat[b]);
      }
      

      为了记录,这里使用的确切重载是函数模板:

      template< class CharT, class traits, class Alloc >
      bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs );
      

      strcmp(这里不需要,在 C++ 中很少需要)需要 const char* 参数:

      int strcmp( const char *lhs, const char *rhs );
      

      所以你可以(但不应该)在c_str() 成员函数的帮助下调用它:

      if(!strcmp(dat[b].c_str(), "String\n") 
      ...
      

      【讨论】:

        【解决方案3】:

        strcmp() 需要 2 个 const char*s 但 dat[b] 是 string,因此您没有将苹果与苹果进行比较。

        你可以这样做

        if(!strcmp(dat[b].c_str(), "String\n"){

        或者

        if (dat[b] == "String\n") {

        第二种是更多的C++方法。

        【讨论】:

          猜你喜欢
          • 2021-03-29
          • 1970-01-01
          • 1970-01-01
          • 2015-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-17
          相关资源
          最近更新 更多