Pointers to elements of std::vector and std::list

后端 未结 7 885
借酒劲吻你
借酒劲吻你 2020-12-05 06:56

I\'m having a std::vector with elements of some class ClassA. Additionally I want to create an index using a std::map

7条回答
  •  执笔经年
    2020-12-05 07:23

    Just make them both store pointers an explicitly delete the objects when you don't need them.

    std::vector storage;
    std::map map;
    
    for (int i=0; i<10000; ++i) {
      ClassA* a = new ClassA()
      storage.push_back(a)
      map.insert(std::make_pair(a->getKey(), a))
    }
    // map contains only valid pointers to the 'correct' elements of storage
    

提交回复
热议问题