NCBI C++ ToolKit
ncbiutil.hpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 #ifndef CORELIB___NCBI_UTILITY__HPP
2 #define CORELIB___NCBI_UTILITY__HPP
3 
4 /* $Id: ncbiutil.hpp 91306 2020-10-08 11:57:15Z gouriano $
5  * ===========================================================================
6  *
7  * PUBLIC DOMAIN NOTICE
8  * National Center for Biotechnology Information
9  *
10  * This software/database is a "United States Government Work" under the
11  * terms of the United States Copyright Act. It was written as part of
12  * the author's official duties as a United States Government employee and
13  * thus cannot be copyrighted. This software/database is freely available
14  * to the public for use. The National Library of Medicine and the U.S.
15  * Government have not placed any restriction on its use or reproduction.
16  *
17  * Although all reasonable efforts have been taken to ensure the accuracy
18  * and reliability of the software and data, the NLM and the U.S.
19  * Government do not and cannot warrant the performance or results that
20  * may be obtained by using this software or data. The NLM and the U.S.
21  * Government disclaim all warranties, express or implied, including
22  * warranties of performance, merchantability or fitness for any particular
23  * purpose.
24  *
25  * Please cite the author in any work or product based on this material.
26  *
27  * ===========================================================================
28  *
29  * Author:
30  * Eugene Vasilchenko
31  *
32  *
33  */
34 
35 /// @file ncbiutil.hpp
36 /// Useful/utility classes and methods.
37 
38 
39 #include <corelib/ncbistd.hpp>
40 #include <memory>
41 #include <map>
42 
43 
44 
46 
47 /** @addtogroup Utility Template Utilities
48  *
49  * @{
50  */
51 
52 //-------------------------------------------
53 // Utilities
54 
55 /// Check for equality of objects pointed to by pointer.
56 template <class T>
57 struct p_equal_to
58 {
59  bool operator() (const T* x, const T* y) const {
60  return *x == *y;
61  }
62 };
63 
64 /// Compare objects pointed to by (smart) pointer.
65 template <class T>
66 struct PPtrLess
67 {
68  bool operator() (const T& x, const T& y) const {
69  return *x < *y;
70  }
71 };
72 
73 /// Check whether a pair's second element matches a given value.
74 template <class Pair>
76 {
77  bool operator() (const Pair& x,
78  const typename Pair::second_type& y) const {
79  return x.second == y;
80  }
81 };
82 
83 /// Check for not null value (after C malloc, strdup etc.).
84 template<class X>
85 inline X* NotNull(X* object)
86 {
87  if ( !object ) {
89  }
90  return object;
91 }
92 
93 /// Get map element (pointer) or NULL if absent.
94 template<class Key, class Element>
95 inline Element GetMapElement(const map<Key, Element>& m, const Key& key,
96  const Element& def = 0)
97 {
98  typename map<Key, Element>::const_iterator ptr = m.find(key);
99  if ( ptr !=m.end() )
100  return ptr->second;
101  return def;
102 }
103 
104 /// Set map element -- if data is null, erase the existing key.
105 template<class Key, class Element>
106 inline void SetMapElement(map<Key, Element*>& m, const Key& key, Element* data)
107 {
108  if ( data )
109  m[key] = data;
110  else
111  m.erase(key);
112 }
113 
114 /// Insert map element.
115 template<class Key, class Element>
117  const Key& key, Element* data)
118 {
119  return m.insert(map<Key, Element*>::value_type(key, data)).second;
120 }
121 
122 /// Get string map element or "" if absent.
123 template<class Key>
124 inline string GetMapString(const map<Key, string>& m, const Key& key)
125 {
126  typename map<Key, string>::const_iterator ptr = m.find(key);
127  if ( ptr != m.end() )
128  return ptr->second;
129  return string();
130 }
131 
132 /// Set string map element -- if data is null erase the existing key.
133 template<class Key>
135  const Key& key, const string& data)
136 {
137  if ( !data.empty() )
138  m[key] = data;
139  else
140  m.erase(key);
141 }
142 
143 /// Delete all elements from a container of pointers (list, vector, set,
144 /// multiset); clear the container afterwards.
145 template<class Cnt>
146 inline void DeleteElements( Cnt& cnt )
147 {
148  for ( typename Cnt::iterator i = cnt.begin(); i != cnt.end(); ++i ) {
149  delete *i;
150  }
151  cnt.clear();
152 }
153 
154 /// Delete all elements from map containing pointers; clear container
155 /// afterwards.
156 template<class Key, class Element>
158 {
159  for ( typename map<Key, Element*>::iterator i = m.begin(); i != m.end();
160  ++i ) {
161  delete i->second;
162  }
163  m.clear();
164 }
165 
166 /// Delete all elements from multimap containing pointers; clear container
167 /// afterwards.
168 template<class Key, class Element>
170 {
171  for ( typename map<Key, Element*>::iterator i = m.begin(); i != m.end();
172  ++i ) {
173  delete i->second;
174  }
175  m.clear();
176 }
177 
178 /// Retrieve the result from the result cache - if cache is empty,
179 /// insert into cache from the supplied source.
180 template<class Result, class Source, class ToKey>
181 inline
182 Result&
183 AutoMap(unique_ptr<Result>& cache, const Source& source, const ToKey& toKey)
184 {
185  Result* ret = cache.get();
186  if ( !ret ) {
187  cache.reset(ret = new Result);
188  for ( typename Source::const_iterator i = source.begin();
189  i != source.end();
190  ++i ) {
191  ret->insert(Result::value_type(toKey.GetKey(*i), *i));
192  }
193  }
194  return *ret;
195 }
196 
197 /// Get name attribute for Value object.
198 template<class Value>
200 {
201  const string& GetKey(const Value* value) const
202  {
203  return value->GetName();
204  }
205 };
206 
207 // These templates may yield 0 if no (suitable) elements exist. Also,
208 // in part for consistency with the C Toolkit, lower scores are
209 // better, and earlier elements win ties.
210 
211 
212 
213 /// Tracks the best score (lowest value).
214 ///
215 /// Values are specified by template parameter T, and scoring function by
216 /// template parameter F.
217 template <typename T, typename F>
219 {
220 public:
221  /// Constructor.
223  { }
224 
225  /// Define application operator.
226  void operator() (const T& x)
227  {
228  int score = m_Func(x);
229  if (score < m_Score) {
230  m_Value = x;
231  m_Score = score;
232  }
233  }
234 
235  /// Get best choice with lowest score.
236  const T& GetBestChoice() { return m_Value; }
237 
238 private:
239  F m_Func; ///< Scoring function
240  T m_Value; ///< Current best value
241  int m_Score; ///< Current best score
242 };
243 
244 /// Find the best choice (lowest score) for values in a container.
245 ///
246 /// Container and scoring functions are specified as template parameters.
247 template <typename C, typename F>
248 inline
249 typename C::value_type
250 FindBestChoice(const C& container, F score_func)
251 {
252  typedef typename C::value_type T;
253  CBestChoiceTracker<T, F> tracker(score_func);
254  ITERATE (typename C, it, container) {
255  tracker(*it);
256  }
257  return tracker.GetBestChoice();
258 }
259 
260 
262 
263 #if !defined(HAVE_IS_SORTED)
264 
265 ///
266 /// is_sorted is provided by some implementations of the STL and may
267 /// be included in future releases of all standard-conforming implementations
268 /// This is provided here for future compatibility
269 ///
270 
272 
273 template <class Iterator>
274 bool is_sorted(Iterator iter1, Iterator iter2)
275 {
276  Iterator prev = iter1;
277  for (++iter1; iter1 != iter2; ++iter1, ++prev) {
278  if (*iter1 < *prev) {
279  return false;
280  }
281  }
282  return true;
283 }
284 
285 
286 template <class Iterator, class Predicate>
287 bool is_sorted(Iterator iter1, Iterator iter2, Predicate pred)
288 {
289  Iterator prev = iter1;
290  for (++iter1; iter1 != iter2; ++iter1, ++prev) {
291  if (pred(*iter1, *prev)) {
292  return false;
293  }
294  }
295  return true;
296 }
297 
298 
300 
301 #endif // !defined(HAVE_IS_SORTED)
302 
303 
304 
305 /* @} */
306 
307 #endif /* NCBI_UTILITY__HPP */
Tracks the best score (lowest value).
Definition: ncbiutil.hpp:219
CCoreException –.
Definition: ncbiexpt.hpp:1476
void erase(iterator pos)
Definition: map.hpp:167
container_type::const_iterator const_iterator
Definition: map.hpp:53
container_type::iterator iterator
Definition: map.hpp:54
const_iterator begin() const
Definition: map.hpp:151
const_iterator end() const
Definition: map.hpp:152
iterator_bool insert(const value_type &val)
Definition: map.hpp:165
container_type::value_type value_type
Definition: map.hpp:52
void clear()
Definition: map.hpp:169
const_iterator find(const key_type &key) const
Definition: map.hpp:153
Definition: map.hpp:338
void clear()
Definition: map.hpp:309
const_iterator end() const
Definition: map.hpp:292
const_iterator begin() const
Definition: map.hpp:291
Include a standard set of the NCBI C++ Toolkit most basic headers.
#define C(s)
Definition: common.h:231
#define T(s)
Definition: common.h:230
static DLIST_TYPE *DLIST_NAME() prev(DLIST_LIST_TYPE *list, DLIST_TYPE *item)
Definition: dlist.tmpl.h:61
char data[12]
Definition: iconv.c:80
#define ITERATE(Type, Var, Cont)
ITERATE macro to sequence through container elements.
Definition: ncbimisc.hpp:815
string
Definition: cgiapp.hpp:690
#define NCBI_THROW(exception_class, err_code, message)
Generic macro to throw an exception, given the exception class, error code and message string.
Definition: ncbiexpt.hpp:704
#define kMax_Int
Definition: ncbi_limits.h:184
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:103
#define BEGIN_STD_SCOPE
Place it for adding new funtionality to STD scope.
Definition: ncbistl.hpp:92
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:100
#define END_STD_SCOPE
End previously defined STD scope.
Definition: ncbistl.hpp:95
#define kEmptyStr
Definition: ncbistr.hpp:123
CBestChoiceTracker(F func)
Constructor.
Definition: ncbiutil.hpp:222
C::value_type FindBestChoice(const C &container, F score_func)
Find the best choice (lowest score) for values in a container.
Definition: ncbiutil.hpp:250
BEGIN_STD_SCOPE bool is_sorted(Iterator iter1, Iterator iter2)
is_sorted is provided by some implementations of the STL and may be included in future releases of al...
Definition: ncbiutil.hpp:274
void SetMapElement(map< Key, Element * > &m, const Key &key, Element *data)
Set map element – if data is null, erase the existing key.
Definition: ncbiutil.hpp:106
bool operator()(const T &x, const T &y) const
Definition: ncbiutil.hpp:68
F m_Func
Scoring function.
Definition: ncbiutil.hpp:239
bool InsertMapElement(map< Key, Element * > &m, const Key &key, Element *data)
Insert map element.
Definition: ncbiutil.hpp:116
X * NotNull(X *object)
Check for not null value (after C malloc, strdup etc.).
Definition: ncbiutil.hpp:85
int m_Score
Current best score.
Definition: ncbiutil.hpp:241
bool operator()(const Pair &x, const typename Pair::second_type &y) const
Definition: ncbiutil.hpp:77
Element GetMapElement(const map< Key, Element > &m, const Key &key, const Element &def=0)
Get map element (pointer) or NULL if absent.
Definition: ncbiutil.hpp:95
void SetMapString(map< Key, string > &m, const Key &key, const string &data)
Set string map element – if data is null erase the existing key.
Definition: ncbiutil.hpp:134
void operator()(const T &x)
Define application operator.
Definition: ncbiutil.hpp:226
const string & GetKey(const Value *value) const
Definition: ncbiutil.hpp:201
Result & AutoMap(unique_ptr< Result > &cache, const Source &source, const ToKey &toKey)
Retrieve the result from the result cache - if cache is empty, insert into cache from the supplied so...
Definition: ncbiutil.hpp:183
bool operator()(const T *x, const T *y) const
Definition: ncbiutil.hpp:59
const T & GetBestChoice()
Get best choice with lowest score.
Definition: ncbiutil.hpp:236
string GetMapString(const map< Key, string > &m, const Key &key)
Get string map element or "" if absent.
Definition: ncbiutil.hpp:124
T m_Value
Current best value.
Definition: ncbiutil.hpp:240
void DeleteElements(Cnt &cnt)
Delete all elements from a container of pointers (list, vector, set, multiset); clear the container a...
Definition: ncbiutil.hpp:146
int i
double value_type
The numeric datatype used by the parser.
Definition: muParserDef.h:228
const struct ncbi::grid::netcache::search::fields::KEY key
const GenericPointer< typename T::ValueType > T2 value
Definition: pointer.h:1227
const CharType(& source)[N]
Definition: pointer.h:1149
GenericValue< UTF8<> > Value
GenericValue with UTF8 encoding.
Definition: document.h:2107
#define F(x)
Make a parametrized function appear to have only one variable.
Definition: ncbi_math.c:342
static unsigned cnt[256]
Get name attribute for Value object.
Definition: ncbiutil.hpp:200
Compare objects pointed to by (smart) pointer.
Definition: ncbiutil.hpp:67
Check for equality of objects pointed to by pointer.
Definition: ncbiutil.hpp:58
Check whether a pair's second element matches a given value.
Definition: ncbiutil.hpp:76
Modified on Fri Sep 20 14:57:47 2024 by modify_doxy.py rev. 669887