首页 > 解决方案 > 搜索记录集/更新值

问题描述

我使用结构、向量创建了一个记录集并添加了几条记录。这是执行此操作的代码。这应该在 Arduino/ESP8266/ESP32 上按原样运行。

#include <string>
#include <vector>

struct student {

  std::string studentName; // I only load this once at startup. So can be const
  std::string studentSlot; // <= This should be updateable
  bool wasPresent;         // <= This should be updateable

  student(const char* stName, const char* stSlot, bool stPresent) :
    studentName(stName),
    studentSlot(stSlot),
    wasPresent(stPresent)
  {}
};

std::vector<student> studentRecs;

void setup() {
  delay(1000);

  Serial.begin(115200);

  // Add couple of records
  student record1("K.Reeves", "SLT-AM-03", false);
  student record2("J.Wick", "SLT-PM-01", true);

  studentRecs.push_back(record1);
  studentRecs.push_back(record2);
}

void loop() {

  Serial.println();

  // Get the size
  int dsize = static_cast<int>(studentRecs.size());

  // Loop, print the records
  for (int i = 0; i < dsize; ++i) {
    Serial.print(studentRecs[i].studentName.c_str());
    Serial.print(" ");
    Serial.print(studentRecs[i].studentSlot.c_str());
    Serial.print(" ");
    Serial.println(String(studentRecs[i].wasPresent));
  }

  // Add a delay, continue with the loop()
  delay(5000);
}

我可以使用 for 循环读取各个记录。我不确定这是否是最好的方法,但它确实有效。

我需要能够在这个记录集上做几件事。

1) 通过 搜索/查找记录studentName。我可以通过循环找到它,但这对我来说效率低下+丑陋。

2)能够更新studentSlotwasPresent

通过一些研究和实验,我发现我可以这样做来改变wasPresent

studentRecs[0].wasPresent = false;

同样,我不确定这是否是最好的方法,但它确实有效。我希望能够改变studentSlot,但我不确定,因为这是我第一次处理结构和向量。studentName 是常量(我只需要在启动时加载一次),studentSlot 可以在运行时更改。我不知道如何改变它。它可能需要我删除 const char*,做一些 strcpy 事情或其他事情,但我被困在那里。简而言之,有 3 件事我需要一点帮助

1) 通过 studentName 搜索/查找记录

2)能够更新studentSlot

3) 删除所有记录。注意:我刚刚发现这样studentRecs.clear()

我不确定我是否能够足够清楚地解释这一点。所以有什么问题请拍。谢谢。

标签: c++vectorstructesp32

解决方案


好吧,我认为您最好的选择是使用for循环搜索studentName. 根据您使用的 C++ 版本:

student searchForName(const std::string & name)
{
    for (auto item : studentRecs)
    {
        if (item.studentName == name)
            return item;
    }
    return student();
}

或者如果您受限于 C++11 之前的版本:

student searchForName(const std::string & name)
{
    for (std::size_t cnt = 0; cnt < studentRecs.size(); ++cnt)
    {
        if (studentRecs[cnt].studentName == name)
            return item;
    }
    return student();
}

其余的非常相似。

顺便说一句。:您可以更改:

...
  // Get the size
  int dsize = static_cast<int>(studentRecs.size());

  // Loop, print the records
  for (int i = 0; i < dsize; ++i) {
...

至:

...
  // Loop, print the records
  for (std::size_t i = 0; i < studentRecs.size(); ++i) {
...

推荐阅读