1. 程式人生 > >c++中刪除迭代器指向的元素後,迭代器指向的被刪除元素後面的元素

c++中刪除迭代器指向的元素後,迭代器指向的被刪除元素後面的元素

1.  C++向容器中插入和刪除元素的時候,迭代器會失效,下面是正確刪除容器元素的做法

void StatsServer::removeExpiredWorkers() {
  size_t expiredWorkerCount = 0;
  size_t expiredUserCount = 0;

  pthread_rwlock_wrlock(&rwlock_);  // write lock

  // delete all expired workers
  for (auto itr = workerSet_.begin(); itr != workerSet_.end(); ) {
    const int32_t userId   = itr->first.userId_;
    shared_ptr<WorkerShares> workerShare = itr->second;

    if (workerShare->isExpired()) {
      itr = workerSet_.erase(itr);

      expiredWorkerCount++;
      totalWorkerCount_--;
      userWorkerCount_[userId]--;
      
      if (userWorkerCount_[userId] <= 0) {
        userWorkerCount_.erase(userId);
      }
    } else {
      itr++;
    }
  }

  // delete all expired users
  for (auto itr = userSet_.begin(); itr != userSet_.end(); ) {
    shared_ptr<WorkerShares> workerShare = itr->second;

    if (workerShare->isExpired()) {
      itr = userSet_.erase(itr);

      expiredUserCount++;
      totalUserCount_--;
    } else {
      itr++;
    }
  }

  pthread_rwlock_unlock(&rwlock_);

  LOG(INFO) << "removed expired workers: " << expiredWorkerCount << ", users: " << expiredUserCount;
}

2. 遍歷讀取容器的元素的寫法如下

for(auto itr = vec.begin(); itr != vec.end(); ++itr)
{
    read(*itr);
}