c++ - 在记录集中搜索/更新值

标签 c++ vector struct esp32

我使用结构、 vector 创建了一个记录集并添加了一些记录。这是执行此操作的代码。这应该按原样运行 - 在 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 但我不确定,因为这是我第一次处理结构和 vector 。 studentName 是常量(我只需要在启动时加载一次),其中 studentSlot 可以在运行时更改。我不确定如何更改它。它可能需要我删除 const char*,做一些 strcpy 之类的事情,但我坚持这样做。简而言之,有 3 件事我需要一点帮助

1) 按学生姓名搜索/查找记录

2) 能够更新studentSlot

3) 删除所有记录。 注意:我刚刚发现 studentRecs.clear() 可以做到这一点

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

最佳答案

嗯,我认为最好的办法是使用 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) {
...

关于c++ - 在记录集中搜索/更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55740114/

相关文章:

c++ - 关于面向对象规划的建议

c++ - 如何将二进制文件读入无符号字符 vector

c++ - 递归 vector 模板

c - Printf 未显示并返回值 3221225477

c - 如何在 C 中初始化双指针? (指针数组)

c++ - 对 vector 进行二进制排序

c++ - 通过ODBC创建数据库

c++ - 不应该存在的随机未解析外部符号

c++ - 获取邻接表中的元素

c++ - 无法将 {...} 从 <brace-enclosed initializer list> 转换为 struct