代码之家  ›  专栏  ›  技术社区  ›  Kaizer Sozay

如何从无序的集合中准确地得到一个元素?

  •  1
  • Kaizer Sozay  · 技术社区  · 6 年前

    我有:

        std::unordered_set<ObjectRepresentation*> incompletePieces;
    

    我只想从无序的集合中得到一个对象。为此,我在循环的末尾使用了for循环和break,这样循环最多只能运行一次。

        while (incompletePieces.size()){
            for (auto containedPiece : incompletePieces){ //Warning at this line that loop will run at most once
                //  .... doing some stuff with the contained piece
                incompletePieces.erase(containedPiece);
    
                        break;
            }
        }
    

    这是我想要的行为。问题是编译器显示警告:

    循环最多运行一次(循环增量从未执行)

    如何重写代码以使警告消失?有没有更好的方法从无序的集合中获得物品?

    4 回复  |  直到 6 年前
        1
  •  4
  •   Gaurav Sehgal    6 年前

    begin()

    if (incompletePieces.size() > 0)
        auto containedPiece = *(incompletePieces.begin());
    
        2
  •  2
  •   Sebastian Redl    6 年前

    incompletePieces

    for (auto piece : incompletePieces) {
      // process piece
    }
    incompletePieces.clear();
    

    auto it = incompletePieces.begin();
    while (it != incompletePieces.end()) {
      // process *it
    #if C++11
      it = incompletePieces.erase(it);
    #else
      auto prev = it++;
      incompletePieces.erase(prev);
    #endif
    }
    
        3
  •  2
  •   Jarod42    6 年前

    *unordered_set::begin() unordered_set::front()

    while (incompletePieces.size()){
        for (auto containedPiece : incompletePieces){
            //  .... doing some stuff with the contained piece
            incompletePieces.erase(containedPiece);
            break;
        }
    }
    

    for (auto* containedPiece : incompletePieces){
        //  .... doing some stuff with the contained piece
    }
    incompletePieces.clear();
    
        4
  •  2
  •   Shrikanth N    6 年前

    for(auto* containedPiece : incompletePieces){
         //Process the set contents
    }
    //Clear entire set in one go 
    incompletePieces.clear();
    

     auto it = incompletePieces.begin(); //Take the pointer to first element of set
     for( ; it !=incompletePieces.end() ; it++){ 
         incompletePieces.erase(*it); //Erase one element at a time
     }