source: src/Fragmentation/Summation/SortedVector.hpp@ 063fab

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 063fab was 063fab, checked in by Frederik Heber <heber@…>, 12 years ago

Added SortedVector and use in IndexSetContainer.

  • the SortedVector is meant if access is frequent and insert is seldom, i.e. basically the set is given to the cstor and little change is made afterwards.
  • SortedVector<T>::Comparator is specific internal functor; this way the functor can be used outside in SubsetMap for its internal map with IndexSet_ptr as keys.
  • IndexSetContainer has member typedef ptr to shared_ptr.
  • added unit test.
  • Property mode set to 100644
File size: 4.1 KB
Line 
1/*
2 * SortedVector.hpp
3 *
4 * Created on: Jul 3, 2012
5 * Author: heber
6 */
7
8#ifndef SORTEDVECTOR_HPP_
9#define SORTEDVECTOR_HPP_
10
11
12// include config.h
13#ifdef HAVE_CONFIG_H
14#include <config.h>
15#endif
16
17#include <algorithm>
18#include <boost/lambda/lambda.hpp>
19#include <boost/shared_ptr.hpp>
20#include <boost/bind.hpp>
21#include <vector>
22
23/** Functor for transforming instance of type T to copies contained in shared_ptr.
24 *
25 */
26template <typename T>
27struct SharedPtrAllocator {
28 boost::shared_ptr<T> operator()(const T& a) {
29 return boost::shared_ptr<T>( new T(a) );
30 }
31};
32
33
34/** This class represents a general sorted container of instances, stored as shared_ptr.
35 *
36 * These instances are stored in order not by appearance memory due to shared_ptr but
37 * by the comparison operators of the underlying type.
38 *
39 * The sorted vector is truely a sorted vector. Hence, we must access often but change
40 * only seldomly. This is due to item#23 in [Meyers, "Effective STL"].
41 *
42 */
43template <typename T>
44struct SortedVector
45{
46 typedef typename T::ptr T_ptr;
47 typedef std::vector<T_ptr> Container_t;
48public:
49 /** Constructor from an unsorted vector of instances.
50 *
51 * @param _container unsorted vector of instances
52 */
53 SortedVector(const Container_t &_container) :
54 ContainerSorted(false),
55 container(_container)
56 {
57 sort();
58 }
59
60 /** Constructor from an unsorted vector of instances.
61 *
62 * @param _container unsorted vector of instances
63 */
64 SortedVector(const std::vector<T> &_container) :
65 ContainerSorted(false)
66 {
67 container.resize(_container.size());
68 SharedPtrAllocator<T> allocator;
69 std::transform(_container.begin(), _container.end(),
70 container.begin(), allocator);
71 sort();
72 }
73
74 /** Constructor from a single instance.
75 *
76 * A single instance is automatically sorted.
77 *
78 * @param _instance single instance
79 */
80 SortedVector(T_ptr &_instance) :
81 ContainerSorted(true)
82 {
83 container.push_back(_instance);
84 }
85
86 /** Getter to sorted container.
87 *
88 * This getter is made const only through the virtue of making the member
89 * variables mutable. This is however the only sensible way as to the outside
90 * the container must be treatable as const despite "lazy" resorting on this
91 * read-only access in the background.
92 *
93 * @return const ref to internal sorted container
94 */
95 const Container_t &getContainer() const {
96 if (!ContainerSorted)
97 sort();
98 return container;
99 }
100
101 /** Insert a shared_ptr instance
102 *
103 * We lazily set the container to not sorted, it is sorted on next access.
104 *
105 * @param a instance to insert
106 */
107 void insert(T_ptr &a) {
108 // check if present via binary_search
109 if (!std::binary_search(container.begin(), container.end(), a, Comparator)) {
110 // only insert if not present
111 container.push_back(a);
112 ContainerSorted = false;
113 }
114 }
115
116 /** Insert an instance not wrapped in shared_ptr.
117 *
118 * We lazily set the container to not sorted, it is sorted on next access.
119 *
120 * @param a instance to copy and insert
121 */
122 void insert(const T &a) {
123 T_ptr ptr(new IndexSet(a));
124 // check if present via binary_search
125 if (!std::binary_search(container.begin(), container.end(), ptr, Comparator)) {
126 // only insert if not present
127 container.push_back(ptr);
128 ContainerSorted = false;
129 }
130 }
131
132 /** Internal static Comparator function, passing the check on to comparison
133 * operator of underlying type.
134 * @param a First instance
135 * @param b Second instance
136 * @return pointee of a < pointee of b
137 */
138 struct Comparator_t {
139 bool operator()(const T_ptr &a, const T_ptr &b) const {
140 return *a < *b;
141 }
142 } Comparator;
143
144private:
145 /** Internal sort function.
146 *
147 */
148 void sort() const {
149 std::sort(container.begin(), container.end(), Comparator);
150 ContainerSorted = true;
151 }
152
153protected:
154 //!> internal flag that container is currently sorted, mutable to let getContainer() be const member function
155 mutable bool ContainerSorted;
156
157private:
158 //!> internal container that is always sorted, mutable to let getContainer() be const member function
159 mutable Container_t container;
160};
161
162
163
164#endif /* SORTEDVECTOR_HPP_ */
Note: See TracBrowser for help on using the repository browser.