PetaVision  Alpha
ObserverTable.cpp
1 /*
2  * ObserverTable.cpp
3  *
4  * Created on: Jul 22, 2016
5  * Author: pschultz
6  */
7 
8 #include "observerpattern/ObserverTable.hpp"
9 #include "utils/PVAssert.hpp"
10 #include <algorithm>
11 
12 namespace PV {
13 
14 std::vector<Observer *>::size_type ObserverTable::size() const {
15  pvAssert(mObjectVector.size() == mObjectMap.size());
16  return mObjectVector.size();
17 }
18 
19 bool ObserverTable::addObject(std::string const &name, Observer *entry) {
20  bool addSucceeded =
21  mObjectMap.insert(std::make_pair(std::string(name), entry)).second; // map::insert()
22  // returns a pair whose
23  // second element is
24  // whether the
25  // insertion was
26  // successful.
27  if (addSucceeded) {
28  mObjectVector.emplace_back(entry);
29  }
30  return addSucceeded;
31 }
32 
33 void ObserverTable::deleteObject(std::string const &name, bool deallocateFlag) {
34  Observer *obj = nullptr;
35  auto mapSearchResult = mObjectMap.find(name);
36  if (mapSearchResult == mObjectMap.end()) {
37  obj = mapSearchResult->second;
38  auto vectorSearchResult = find(mObjectVector.begin(), mObjectVector.end(), obj);
39  pvAssert(vectorSearchResult != mObjectVector.end());
40  mObjectMap.erase(mapSearchResult);
41  mObjectVector.erase(vectorSearchResult);
42  if (deallocateFlag) {
43  delete obj;
44  }
45  }
46 }
47 
48 void ObserverTable::clear(bool deallocateFlag) {
49  if (deallocateFlag) {
50  for (auto &obj : mObjectVector) {
51  delete obj;
52  }
53  }
54  mObjectVector.clear();
55  mObjectMap.clear();
56 }
57 
58 } /* namespace PV */