首页 文章

如何将字符串与矢量值进行比较?

提问于
浏览
0

如何在a向量<std :: 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:在函数_2401590中:
my.cpp:53:32:错误:无法将'__gnu_cxx::__alloc_traits > >::value_type
'转换为'const char*',参数'1'为'int strcmp(const char*, const char*)'

3 回答

  • 4

    std::string 与plain == 进行比较 . 这是有效的,因为 == 运算符被重载以对 std::string 进行字符串比较 .

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

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

  • 1

    只需使用 operator== 来比较 std::stringconst 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") 
    ...
    
  • 0

    strcmp() 预计2 const char* s但 dat[b]string ,所以你不是在比较苹果和苹果 .

    你可以这样做

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

    要么

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

    第二个是更多的C方法 .

相关问题