在向量中搜索项目

Search item in a vector

我想在我的结构中找到一个元素(姓氏)

struct student
{
    char name[20];
    char surname[20];
    int marks;
};

Ofc 从键盘定义矢量和搜索元素

vector <student> v;
char search_surname[20];

我是按功能输入元素:

    int size = v.size();
    v.push_back(student());
    cout << "Input name: " << endl;
    cin >> v[size].name;
    cout << "Input surname: " << endl;
    cin >> v[size].surname;
    cout << "Input marks: " << endl;
    cin >> v[size].marks;

现在,当我的结构中有例如三个姓氏(牛顿、爱因斯坦、帕斯卡)时,我想找到姓氏牛顿并用牛顿(名字、姓氏、标记)计算结构的所有细节。我不知道该怎么办。

暴力法:

for(vector <student>::iterator it = v.begin(); it != v.end(); it++)
{
    if (strcmp(it->surname, "newton") == 0)
    {
        cout << "name = " << it->name << endl;
        cout << "surname = " << it->surname << endl;
        cout << "marks = " << it->marks << endl;
    }
}

请将 #include <cstring> 添加到您的代码中以便使用 strcmp()

我最近使用了库<算法>中的std::find()

这个函数 return 是一个迭代器,当 return 值不是 end() 时表示找到。

使用 STL,您可以使用 <algorithm> 中的 std::find_if

std::vector<student> v;


auto it = std::find_if(v.begin(), v.end(), [](const student& s)
              {
                  return strcmp(s.surname, "newton") == 0;
              });
if (it != v.end()) {
    std::cout << "name = " << it->name << std::endl;
    std::cout << "surname = " << it->surname << std::endl;
    std::cout << "marks = " << it->marks << std::endl;
}

注意:我建议使用 std::string 而不是 char[20] 这样条件就会变成 return s.surname == "newton".