blob: d503a54358ccedeb5567cdb164ac0928f976cd1e [file] [log] [blame]
Carl Shapiro58551df2011-07-24 03:09:51 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
3#ifndef ART_SRC_STL_UTIL_H_
4#define ART_SRC_STL_UTIL_H_
5
Elliott Hughes14134a12011-09-30 16:55:51 -07006#include <iostream>
7
Carl Shapiro58551df2011-07-24 03:09:51 -07008namespace art {
9
10// STLDeleteContainerPointers()
11// For a range within a container of pointers, calls delete
12// (non-array version) on these pointers.
13// NOTE: for these three functions, we could just implement a DeleteObject
14// functor and then call for_each() on the range and functor, but this
15// requires us to pull in all of algorithm.h, which seems expensive.
16// For hash_[multi]set, it is important that this deletes behind the iterator
17// because the hash_set may call the hash function on the iterator when it is
18// advanced, which could result in the hash function trying to deference a
19// stale pointer.
20template <class ForwardIterator>
21void STLDeleteContainerPointers(ForwardIterator begin,
22 ForwardIterator end) {
23 while (begin != end) {
24 ForwardIterator temp = begin;
25 ++begin;
26 delete *temp;
27 }
28}
29
30// STLDeleteElements() deletes all the elements in an STL container and clears
31// the container. This function is suitable for use with a vector, set,
32// hash_set, or any other STL container which defines sensible begin(), end(),
33// and clear() methods.
34//
35// If container is NULL, this function is a no-op.
36//
37// As an alternative to calling STLDeleteElements() directly, consider
38// ElementDeleter (defined below), which ensures that your container's elements
39// are deleted when the ElementDeleter goes out of scope.
40template <class T>
41void STLDeleteElements(T *container) {
42 if (!container) return;
43 STLDeleteContainerPointers(container->begin(), container->end());
44 container->clear();
45}
46
Elliott Hughesc31664f2011-09-29 15:58:28 -070047// Given an STL container consisting of (key, value) pairs, STLDeleteValues
48// deletes all the "value" components and clears the container. Does nothing
49// in the case it's given a NULL pointer.
50template <class T>
51void STLDeleteValues(T *v) {
52 if (!v) return;
53 for (typename T::iterator i = v->begin(); i != v->end(); ++i) {
54 delete i->second;
55 }
56 v->clear();
57}
58
Elliott Hughes14134a12011-09-30 16:55:51 -070059template <class T>
60std::string ToString(const T& v) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070061 std::ostringstream os;
Elliott Hughes14134a12011-09-30 16:55:51 -070062 os << "[";
63 for (size_t i = 0; i < v.size(); ++i) {
64 os << v[i];
65 if (i < v.size() - 1) {
66 os << ", ";
67 }
68 }
69 os << "]";
70 return os.str();
71}
72
Carl Shapiro58551df2011-07-24 03:09:51 -070073} // namespace art
74
75#endif // ART_SRC_STL_UTIL_H_