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

Last change on this file since 1340 was 1340, checked in by Maciej Komosinski, 2 days ago

Added helper functions

File size: 1.9 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 1999-2025  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
30// c++17 implementation of c++20 std::vector::erase_if()
31template<typename T,typename P> void erase_if(vector<T>& v, P predicate)
32{
33        v.erase(std::remove_if(v.begin(), v.end(), predicate), v.end());
34}
35
36template<typename T> void deleteVectorElements(vector<T*>& v)
37{
38        for (typename vector<T*>::iterator it = v.begin(); it != v.end(); it++)
39                delete *it;
40        v.clear();
41}
42
43template<typename T> int findIndex(vector<T>& v, const T& e)
44{
45        typename vector<T>::iterator it = find(v.begin(), v.end(), e);
46        if (it != v.end())
47                return int(&*it - &v.front());
48        return -1;
49}
50
51template<typename Key, typename Value> Value mapValueOrDefault(const std::map<Key, Value> &map, const Key& key, const Value& default_value)
52{
53        auto found = map.find(key);
54        if (found != map.end())
55                return found->second;
56        else
57                return default_value;
58}
59
60template<class T> class DeletingVector  // deletes the elements (pointers) in destructor
61{
62public:
63        std::vector<T*> vector;
64        ~DeletingVector()
65        {
66                for (int i = (int)vector.size() - 1; i >= 0; i--)
67                        delete vector[i];
68        }
69        T* operator[](int i) { return vector[i]; }
70        int size() { return vector.size(); }
71        void push_back(T* x) { vector.push_back(x); }
72};
73
74#endif
Note: See TracBrowser for help on using the repository browser.