source: cpp/common/util-stl.h @ 1298

Last change on this file since 1298 was 1288, checked in by Maciej Komosinski, 11 months ago

Added helper functions

File size: 1.7 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2023  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#ifndef _UTIL_STL_H_
6#define _UTIL_STL_H_
7
8#include <map>
9#include <algorithm>
10
11template<typename T, std::size_t N> void push_back(vector<T>& v, T(&d)[N])
12{
13        for (unsigned int i = 0; i < N; i++)
14                v.push_back(d[i]);
15}
16
17template<typename T> void push_back(vector<T>& to, const vector<T>& from)
18{
19        for (auto &e : from)
20                to.push_back(e);
21}
22
23template<typename T> void erase(vector<T>& v, const T& e)
24{
25        typename vector<T>::iterator it = std::find(v.begin(), v.end(), e);
26        if (it != v.end())
27                v.erase(it);
28}
29
30template<typename T> void deleteVectorElements(vector<T*>& v)
31{
32        for (typename vector<T*>::iterator it = v.begin(); it != v.end(); it++)
33                delete *it;
34        v.clear();
35}
36
37template<typename T> int findIndex(vector<T>& v, const T& e)
38{
39        typename vector<T>::iterator it = find(v.begin(), v.end(), e);
40        if (it != v.end())
41                return int(&*it - &v.front());
42        return -1;
43}
44
45template<typename Key, typename Value> Value mapValueOrDefault(const std::map<Key, Value> &map, const Key& key, const Value& default_value)
46{
47        auto found = map.find(key);
48        if (found != map.end())
49                return found->second;
50        else
51                return default_value;
52}
53
54template<class T> class DeletingVector  // deletes the elements (pointers) in destructor
55{
56public:
57        std::vector<T*> vector;
58        ~DeletingVector()
59        {
60                for (int i = (int)vector.size() - 1; i >= 0; i--)
61                        delete vector[i];
62        }
63        T* operator[](int i) { return vector[i]; }
64        int size() { return vector.size(); }
65        void push_back(T* x) { vector.push_back(x); }
66};
67
68#endif
Note: See TracBrowser for help on using the repository browser.