Search vector of structs

China☆狼群 提交于 2021-02-11 14:01:08

问题


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


回答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.



来源:https://stackoverflow.com/questions/59781200/search-vector-of-structs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!