[C++]vector指定した要素を削除

3643 ワード

背景
最近、仕事中に問題が発生しました.問題は以下のように簡略化されます.
推奨システムでは、あるuserのリコール候補itemのセットをスコアリングしてソートし、itemのセットをリコールリストvectorに格納します.実装する必要がある機能は、itemリストをリコールしてモデルの採点に送る前に、フィルタリングを行うことです.すなわちuserがすでに所有しているitemについては,これらのitemをモデルに送り込んで採点しない.
たとえば、user 1はすでにitem 1、item 2を持っています.リコールリストvectorのitem 1,item 2をフィルタリングする必要があります.
ソリューション
int32_t filter_number = 0;
std::set<int64_t> user_already_ow_item_set;
vector<ItemInfo>::iterator it;
for (it = item_recall_list.begin(); it != item_recall_list.end();) {
    if (user_already_own_item_set.find((*it).item_id) != user_already_own_item_set.end()) {
      it = item_recall_list.erase(it); //     item_recall_list.erase(it);
      filter_number++;
    } else {
      ++it;	// 
    }
}

インテリジェントポイント
C++vectorでは、実際に要素を削除するにはコンテナvecrotでstd::vector::erase()メソッドを使用します.std::remove()は要素を削除しません.容器のsize()は変化しません.要素の置換だけです.
  • std::vector::erase()関数プロトタイプ:iterator erase(iterator position);//指定した要素iterator erase(iterator first,iterator last)を削除します.//指定した範囲内の要素の戻り値の削除:削除した要素(または範囲)の次の要素を指します.(An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.)