0

I'm trying to find a string within in a vector of structs. But I keep getting an error, the error message is way too long so Ill upload it externally. A part of it is

"error: no match for 'operator==' (operand types are 'char' and 'const std::__cxx11::basic_string') { return *__it == _M_value; }"

The code Im currently using is:

struct constants {
    std::string name, lastname;
    float salary=0;
};

void searchPerson(const std::vector<constants> &search) {
    using namespace std;
    vector<constants>name;
    string searchTerm;
    cout << "Enter last name of the person you wish you lookup." << "\n";
    cin >> searchTerm;
for (size_t k=0; k<name.size(); k++){
    if (std::find(name[k].lastname.begin(), name[k].lastname.end(), searchTerm) != name[k].lastname.end())
    {
        cout << "Test" << "\n";
    }
  }
}

I just cant seem to get it working, I don't know whats wrong. The end goal is to let the user input the last name of a person, if theres a person with that last name stored in the program, it will print all the information about that person (first name, last name and salary). I will probably also be using the same search technique to delete a person from the program.

I can easily get it working by simply using a for loop, but there should definitely be a reason for using the find syntax, The below snippet work wonders.

for (size_t i=0; i<name.size(); i++) {
    if (name[i].lastname== searchTerm)
        cout << "Test" << "\n";
}

https://pastebin.com/mk0pTWgr

Trollblod
  • 27
  • 6

1 Answers1

1

The isn't doing what you think it is. It's a for loop that iterates a vector of constants and tries to search within lastname of each individual constants object. I don't think you mean to do this. You can simply compare the lastname with searchTerm like this:

for (size_t k = 0; k < name.size(); k++) {
    if (name[k].lastname == searchTerm)
    {
        std::cout << "Test" << "\n";
        break;
    }
}

However, hand-crafted for loops are best avoided with stl collections like std::vector. You could use std::find but that will make use of an operator == within your struct. You will either have to provide or you could use std::find_if instead and supply a predicate function to do the comparison:

if (std::find_if(name.cbegin(), name.cend(),
        [&searchTerm](const constants& c) { return searchTerm == c.lastname; }) != name.end())
{
    std::cout << "Test" << "\n";
}

This will avoid the use of a for loop. Note that a lambda function is the predicate, which captures your searchTerm by reference and compares it with lastname only.

jignatius
  • 6,304
  • 2
  • 15
  • 30
  • This worked just like it should, thanks a lot for the help. I've been sitting for 12 hours straight and maybe a pause is due. Thanks once again! Felt like bad practice using a for loop here. – Trollblod Jan 17 '20 at 05:29
  • 1
    @Trollblod No problem. I'm glad I was able to help and you learnt something. – jignatius Jan 17 '20 at 05:31