迭代 - Iteration

迭代 - Iteration

下面的例子演示了如何从数据库中成对的打印键值:

  1. 1. leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
  2. 2. for (it->SeekToFirst(); it->Valid(); it->Next()) {
  3. 3. cout << it->key().ToString() << ": " << it->value().ToString() << endl;
  4. 4. }
  5. 5. assert(it->status().ok()); // Check for any errors found during the scan
  6. 6. delete it;

下面的修改后的例子演示了如何仅获取[start, limit)范围内的键;

  1. 1. for (it->Seek(start);
  2. 2. it->Valid() && it->key().ToString() < limit;
  3. 3. it->Next()) {
  4. 4. ...
  5. 5. }

还可以通过相反的顺序进行处理。(警告:反向迭代比正向迭代慢一些)

  1. 1. for (it->SeekToLast(); it->Valid(); it->Prev()) {
  2. 2. ...
  3. 3. }