搜索记录集/更新值

问题描述 投票:0回答:1

我使用结构,向量和添加了几个记录创建了一个记录集。这是执行它的代码。这应该按原样运行 - 在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 thingy或者其他东西,但我坚持这一点。总之,我需要一些帮助

1)按studentName搜索/查找记录

2)能够更新studentSlot

3)删除所有记录。注意:我只是想通了studentRecs.clear()这样做

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

c++ vector struct esp32
1个回答
2
投票

好吧,我认为你最好的选择是使用for循环搜索studentName。取决于您使用的C ++版本:

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

或者如果你被限制在pre-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) {
...
© www.soinside.com 2019 - 2024. All rights reserved.