C++ – How to compare a string to a vector value

cc++11stringvector

How to you do a string comparison in a to a value in a vector<std::string>?

I tried str, the error is printed below.

…..

    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: In function 'std::vector > ngr()':
my.cpp:53:32: error: cannot convert '__gnu_cxx::__alloc_traits > >::value_type {aka std::basic_string}' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'

Best Answer

std::string is compared with plain ==. This works because the == operator is overloaded to do a string comparison for std::strings.

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

If you're dealing with C++ strings, you shouldn't need any of the str* functions from string.h, so you might as well not include it at all.