【问题标题】:Search item in a vector在向量中搜索项目
【发布时间】:2016-04-01 07:51:43
【问题描述】:

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

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;

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

【问题讨论】:

    标签: c++ algorithm vector struct find


    【解决方案1】:

    使用 STL,您可以使用来自 &lt;algorithm&gt;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"

    【讨论】:

      【解决方案2】:

      我最近使用了库中的std::find()

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

      【讨论】:

        【解决方案3】:

        蛮力方法:

        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 &lt;cstring&gt;,以便使用strcmp()

        【讨论】:

          猜你喜欢
          • 2011-08-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多