Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

[027967]: libutil++ / sparse_array.h Maximize Restore History

Download this file

sparse_array.h    96 lines (78 with data), 2.5 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* @file sparse_array.h
* Auto-expanding sparse array type
*
* @remark Copyright 2007 OProfile authors
* @remark Copyright (c) International Business Machines, 2007.
* @remark Read the file COPYING
*
* @author Dave Nomura <dcnltc@us.ibm.com>
*/
#ifndef SPARSE_ARRAY_H
#define SPARSE_ARRAY_H
template <typename I, typename T> class sparse_array {
public:
typedef std::map<I, T> container_type;
typedef typename container_type::size_type size_type;
/**
* Index into the map for a value.
* NOTE: since std::map does/can not have a const member function for
* operator[], this const member function simply returns 0 for
* profile classes that aren't represented in the map.
* This member function will only be invoked for queries of the
* sparse array.
*/
T operator[](size_type index) const {
typename container_type::const_iterator it = container.find(index);
if (it != container.end())
return it->second;
else
return 0;
}
/**
* Index into the vector for a value. If the index is larger than
* the current max index, a new array entry is created.
*/
T & operator[](size_type index) {
return container[index];
}
/**
* vectorized += operator
*/
sparse_array & operator+=(sparse_array const & rhs) {
typename container_type::const_iterator it = rhs.container.begin();
typename container_type::const_iterator it_end = rhs.container.end();
for ( ; it != it_end; it++)
container[it->first] += it->second;
return *this;
}
/**
* vectorized -= operator, overflow shouldn't occur during substraction
* (iow: for each components lhs[i] >= rhs[i]
*/
sparse_array & operator-=(sparse_array const & rhs) {
typename container_type::const_iterator it = rhs.container.begin();
typename container_type::const_iterator it_end = rhs.container.end();
for ( ; it != it_end; it++)
container[it->first] -= it->second;
return *this;
}
/// return current size of array
size_type size() const {
typename container_type::const_iterator last = container.end();
--last;
return last->first;
}
/// return true if all elements have the default constructed value
bool zero() const {
typename container_type::const_iterator it = container.begin();
typename container_type::const_iterator it_end = container.end();
for ( ; it != it_end; it++)
if (it->second != 0)
return false;
return true;
}
private:
container_type container;
};
#endif // SPARSE_ARRAY_H