Global.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. #pragma once
  2. /*
  3. * Global.h, part of VCMI engine
  4. *
  5. * Authors: listed in file AUTHORS in main folder
  6. *
  7. * License: GNU General Public License v2.0 or later
  8. * Full text of license available in license.txt file, in main folder
  9. *
  10. */
  11. /* ---------------------------------------------------------------------------- */
  12. /* Compiler detection */
  13. /* ---------------------------------------------------------------------------- */
  14. // Fixed width bool data type is important for serialization
  15. static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size.");
  16. #ifdef __GNUC__
  17. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__)
  18. #endif
  19. #if !defined(__clang__) && defined(__GNUC__) && (GCC_VERSION < 470)
  20. # error VCMI requires at least gcc-4.7.2 for successful compilation or clang-3.1. Please update your compiler
  21. #endif
  22. #if defined(__GNUC__) && (GCC_VERSION == 470 || GCC_VERSION == 471)
  23. # error This GCC version has buggy std::array::at version and should not be used. Please update to 4.7.2 or later
  24. #endif
  25. /* ---------------------------------------------------------------------------- */
  26. /* Suppress some compiler warnings */
  27. /* ---------------------------------------------------------------------------- */
  28. #ifdef _MSC_VER
  29. # pragma warning (disable : 4800 ) /* disable conversion to bool warning -- I think it's intended in all places */
  30. #endif
  31. /* ---------------------------------------------------------------------------- */
  32. /* System detection. */
  33. /* ---------------------------------------------------------------------------- */
  34. // Based on: http://sourceforge.net/p/predef/wiki/OperatingSystems/
  35. // and on: http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor
  36. // TODO?: Should be moved to vstd\os_detect.h (and then included by Global.h)
  37. #ifdef _WIN16 // Defined for 16-bit environments
  38. # error "16-bit Windows isn't supported"
  39. #elif defined(_WIN64) // Defined for 64-bit environments
  40. # define VCMI_WINDOWS
  41. # define VCMI_WINDOWS_64
  42. #elif defined(_WIN32) // Defined for both 32-bit and 64-bit environments
  43. # define VCMI_WINDOWS
  44. # define VCMI_WINDOWS_32
  45. #elif defined(_WIN32_WCE)
  46. # error "Windows CE isn't supported"
  47. #elif defined(__linux__) || defined(__gnu_linux__) || defined(linux) || defined(__linux)
  48. # define VCMI_UNIX
  49. # define VCMI_XDG
  50. # ifdef __ANDROID__
  51. # define VCMI_ANDROID
  52. # endif
  53. #elif defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
  54. # define VCMI_UNIX
  55. # define VCMI_XDG
  56. # define VCMI_FREEBSD
  57. #elif defined(__GNU__) || defined(__gnu_hurd__) || (defined(__MACH__) && !defined(__APPLE__))
  58. # define VCMI_UNIX
  59. # define VCMI_XDG
  60. # define VCMI_HURD
  61. #elif defined(__APPLE__) && defined(__MACH__)
  62. # define VCMI_UNIX
  63. # define VCMI_APPLE
  64. # include "TargetConditionals.h"
  65. # if TARGET_IPHONE_SIMULATOR
  66. # define VCMI_IOS
  67. # define VCMI_IOS_SIM
  68. # elif TARGET_OS_IPHONE
  69. # define VCMI_IOS
  70. # elif TARGET_OS_MAC
  71. # define VCMI_MAC
  72. # else
  73. //# warning "Unknown Apple target."?
  74. # endif
  75. #else
  76. # error "VCMI supports only Windows, OSX, Linux and Android targets"
  77. #endif
  78. #ifdef VCMI_IOS
  79. # error "iOS system isn't yet supported."
  80. #endif
  81. /* ---------------------------------------------------------------------------- */
  82. /* Commonly used C++, Boost headers */
  83. /* ---------------------------------------------------------------------------- */
  84. #ifdef VCMI_WINDOWS
  85. # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - delete this line if something is missing.
  86. # define NOMINMAX // Exclude min/max macros from <Windows.h>. Use std::[min/max] from <algorithm> instead.
  87. # define _NO_W32_PSEUDO_MODIFIERS // Exclude more macros for compiling with MinGW on Linux.
  88. #endif
  89. /* ---------------------------------------------------------------------------- */
  90. /* A macro to force inlining some of our functions */
  91. /* ---------------------------------------------------------------------------- */
  92. // Compiler (at least MSVC) is not so smart here-> without that displaying is MUCH slower
  93. #ifdef _MSC_VER
  94. # define STRONG_INLINE __forceinline
  95. #elif __GNUC__
  96. # define STRONG_INLINE inline __attribute__((always_inline))
  97. #else
  98. # define STRONG_INLINE inline
  99. #endif
  100. #define _USE_MATH_DEFINES
  101. #include <cstdio>
  102. #include <stdio.h>
  103. #include <algorithm>
  104. #include <array>
  105. #include <cassert>
  106. #include <climits>
  107. #include <cmath>
  108. #include <cstdlib>
  109. #include <functional>
  110. #include <fstream>
  111. #include <iomanip>
  112. #include <iostream>
  113. #include <map>
  114. #include <memory>
  115. #include <numeric>
  116. #include <queue>
  117. #include <random>
  118. #include <set>
  119. #include <sstream>
  120. #include <string>
  121. #include <unordered_set>
  122. #include <unordered_map>
  123. #include <utility>
  124. #include <vector>
  125. //The only available version is 3, as of Boost 1.50
  126. #include <boost/version.hpp>
  127. #define BOOST_FILESYSTEM_VERSION 3
  128. #if BOOST_VERSION > 105000
  129. # define BOOST_THREAD_VERSION 3
  130. #endif
  131. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  132. #define BOOST_BIND_NO_PLACEHOLDERS
  133. #include <boost/algorithm/string.hpp>
  134. #include <boost/cstdint.hpp>
  135. #include <boost/current_function.hpp>
  136. #include <boost/crc.hpp>
  137. #include <boost/date_time/posix_time/posix_time.hpp>
  138. #include <boost/date_time/posix_time/posix_time_io.hpp>
  139. #include <boost/filesystem.hpp>
  140. #include <boost/filesystem/path.hpp>
  141. #include <boost/filesystem/fstream.hpp>
  142. #include <boost/format.hpp>
  143. #include <boost/functional/hash.hpp>
  144. #include <boost/lexical_cast.hpp>
  145. #ifndef VCMI_ANDROID
  146. #include <boost/locale/generator.hpp>
  147. #endif
  148. #include <boost/logic/tribool.hpp>
  149. #include <boost/optional.hpp>
  150. #include <boost/optional/optional_io.hpp>
  151. #include <boost/program_options.hpp>
  152. #include <boost/range/adaptor/filtered.hpp>
  153. #include <boost/range/adaptor/reversed.hpp>
  154. #include <boost/range/algorithm.hpp>
  155. #include <boost/thread.hpp>
  156. #include <boost/variant.hpp>
  157. #include <boost/math/special_functions/round.hpp>
  158. #include <boost/multi_array.hpp>
  159. #ifndef M_PI
  160. # define M_PI 3.14159265358979323846
  161. #endif
  162. /* ---------------------------------------------------------------------------- */
  163. /* Usings */
  164. /* ---------------------------------------------------------------------------- */
  165. using std::shared_ptr;
  166. using std::unique_ptr;
  167. using std::make_shared;
  168. using namespace std::placeholders;
  169. namespace range = boost::range;
  170. /* ---------------------------------------------------------------------------- */
  171. /* Typedefs */
  172. /* ---------------------------------------------------------------------------- */
  173. // Integral data types
  174. typedef boost::uint64_t ui64; //unsigned int 64 bits (8 bytes)
  175. typedef boost::uint32_t ui32; //unsigned int 32 bits (4 bytes)
  176. typedef boost::uint16_t ui16; //unsigned int 16 bits (2 bytes)
  177. typedef boost::uint8_t ui8; //unsigned int 8 bits (1 byte)
  178. typedef boost::int64_t si64; //signed int 64 bits (8 bytes)
  179. typedef boost::int32_t si32; //signed int 32 bits (4 bytes)
  180. typedef boost::int16_t si16; //signed int 16 bits (2 bytes)
  181. typedef boost::int8_t si8; //signed int 8 bits (1 byte)
  182. // Lock typedefs
  183. typedef boost::lock_guard<boost::mutex> TLockGuard;
  184. typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
  185. /* ---------------------------------------------------------------------------- */
  186. /* Macros */
  187. /* ---------------------------------------------------------------------------- */
  188. // Import + Export macro declarations
  189. #ifdef VCMI_WINDOWS
  190. # ifdef __GNUC__
  191. # define DLL_IMPORT __attribute__((dllimport))
  192. # define DLL_EXPORT __attribute__((dllexport))
  193. # else
  194. # define DLL_IMPORT __declspec(dllimport)
  195. # define DLL_EXPORT __declspec(dllexport)
  196. # endif
  197. # define ELF_VISIBILITY
  198. #else
  199. # ifdef __GNUC__
  200. # define DLL_IMPORT __attribute__ ((visibility("default")))
  201. # define DLL_EXPORT __attribute__ ((visibility("default")))
  202. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  203. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  204. # endif
  205. #endif
  206. #ifdef VCMI_DLL
  207. # define DLL_LINKAGE DLL_EXPORT
  208. #else
  209. # define DLL_LINKAGE DLL_IMPORT
  210. #endif
  211. #define THROW_FORMAT(message, formatting_elems) throw std::runtime_error(boost::str(boost::format(message) % formatting_elems))
  212. #define ASSERT_IF_CALLED_WITH_PLAYER if(!player) {logGlobal->errorStream() << BOOST_CURRENT_FUNCTION; assert(0);}
  213. // can be used for counting arrays
  214. template<typename T, size_t N> char (&_ArrayCountObj(const T (&)[N]))[N];
  215. #define ARRAY_COUNT(arr) (sizeof(_ArrayCountObj(arr)))
  216. // should be used for variables that becomes unused in release builds (e.g. only used for assert checks)
  217. #define UNUSED(VAR) ((void)VAR)
  218. /* ---------------------------------------------------------------------------- */
  219. /* VCMI standard library */
  220. /* ---------------------------------------------------------------------------- */
  221. #include "lib/logging/CLogger.h"
  222. void inline handleException()
  223. {
  224. try
  225. {
  226. throw;
  227. }
  228. catch(const std::exception & ex)
  229. {
  230. logGlobal->errorStream() << ex.what();
  231. }
  232. catch(const std::string & ex)
  233. {
  234. logGlobal->errorStream() << ex;
  235. }
  236. catch(...)
  237. {
  238. logGlobal->errorStream() << "Sorry, caught unknown exception type. No more info available.";
  239. }
  240. }
  241. template<typename T>
  242. std::ostream & operator<<(std::ostream & out, const boost::optional<T> & opt)
  243. {
  244. if(opt) return out << *opt;
  245. else return out << "empty";
  246. }
  247. template<typename T>
  248. std::ostream & operator<<(std::ostream & out, const std::vector<T> & container)
  249. {
  250. out << "[";
  251. for(auto it = container.begin(); it != container.end(); ++it)
  252. {
  253. out << *it;
  254. if(std::prev(container.end()) != it) out << ", ";
  255. }
  256. return out << "]";
  257. }
  258. namespace vstd
  259. {
  260. // combine hashes. Present in boost but not in std
  261. template <class T>
  262. inline void hash_combine(std::size_t& seed, const T& v)
  263. {
  264. std::hash<T> hasher;
  265. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  266. }
  267. //returns true if container c contains item i
  268. template <typename Container, typename Item>
  269. bool contains(const Container & c, const Item &i)
  270. {
  271. return std::find(std::begin(c), std::end(c),i) != std::end(c);
  272. }
  273. //returns true if container c contains item i
  274. template <typename Container, typename Pred>
  275. bool contains_if(const Container & c, Pred p)
  276. {
  277. return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
  278. }
  279. //returns true if map c contains item i
  280. template <typename V, typename Item, typename Item2>
  281. bool contains(const std::map<Item,V> & c, const Item2 &i)
  282. {
  283. return c.find(i)!=c.end();
  284. }
  285. //returns true if unordered set c contains item i
  286. template <typename Item>
  287. bool contains(const std::unordered_set<Item> & c, const Item &i)
  288. {
  289. return c.find(i)!=c.end();
  290. }
  291. template <typename V, typename Item, typename Item2>
  292. bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
  293. {
  294. return c.find(i)!=c.end();
  295. }
  296. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  297. template <typename Container, typename T2>
  298. int find_pos(const Container & c, const T2 &s)
  299. {
  300. size_t i=0;
  301. for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
  302. if(*iter == s)
  303. return i;
  304. return -1;
  305. }
  306. //Func f tells if element matches
  307. template <typename Container, typename Func>
  308. int find_pos_if(const Container & c, const Func &f)
  309. {
  310. auto ret = boost::range::find_if(c, f);
  311. if(ret != std::end(c))
  312. return std::distance(std::begin(c), ret);
  313. return -1;
  314. }
  315. //returns iterator to the given element if present in container, end() if not
  316. template <typename Container, typename Item>
  317. typename Container::iterator find(Container & c, const Item &i)
  318. {
  319. return std::find(c.begin(),c.end(),i);
  320. }
  321. //returns const iterator to the given element if present in container, end() if not
  322. template <typename Container, typename Item>
  323. typename Container::const_iterator find(const Container & c, const Item &i)
  324. {
  325. return std::find(c.begin(),c.end(),i);
  326. }
  327. //removes element i from container c, returns false if c does not contain i
  328. template <typename Container, typename Item>
  329. typename Container::size_type operator-=(Container &c, const Item &i)
  330. {
  331. typename Container::iterator itr = find(c,i);
  332. if(itr == c.end())
  333. return false;
  334. c.erase(itr);
  335. return true;
  336. }
  337. //assigns greater of (a, b) to a and returns maximum of (a, b)
  338. template <typename t1, typename t2>
  339. t1 &amax(t1 &a, const t2 &b)
  340. {
  341. if(a >= b)
  342. return a;
  343. else
  344. {
  345. a = b;
  346. return a;
  347. }
  348. }
  349. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  350. template <typename t1, typename t2>
  351. t1 &amin(t1 &a, const t2 &b)
  352. {
  353. if(a <= b)
  354. return a;
  355. else
  356. {
  357. a = b;
  358. return a;
  359. }
  360. }
  361. //makes a to fit the range <b, c>
  362. template <typename t1, typename t2, typename t3>
  363. t1 &abetween(t1 &a, const t2 &b, const t3 &c)
  364. {
  365. amax(a,b);
  366. amin(a,c);
  367. return a;
  368. }
  369. //checks if a is between b and c
  370. template <typename t1, typename t2, typename t3>
  371. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  372. {
  373. return value > min && value < max;
  374. }
  375. //checks if a is within b and c
  376. template <typename t1, typename t2, typename t3>
  377. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  378. {
  379. return value >= min && value <= max;
  380. }
  381. template <typename t1, typename t2>
  382. struct assigner
  383. {
  384. public:
  385. t1 &op1;
  386. t2 op2;
  387. assigner(t1 &a1, const t2 & a2)
  388. :op1(a1), op2(a2)
  389. {}
  390. void operator()()
  391. {
  392. op1 = op2;
  393. }
  394. };
  395. // Assigns value a2 to a1. The point of time of the real operation can be controlled
  396. // with the () operator.
  397. template <typename t1, typename t2>
  398. assigner<t1,t2> assigno(t1 &a1, const t2 &a2)
  399. {
  400. return assigner<t1,t2>(a1,a2);
  401. }
  402. //deleted pointer and sets it to nullptr
  403. template <typename T>
  404. void clear_pointer(T* &ptr)
  405. {
  406. delete ptr;
  407. ptr = nullptr;
  408. }
  409. #if _MSC_VER >= 1800
  410. using std::make_unique;
  411. #else
  412. template<typename T>
  413. std::unique_ptr<T> make_unique()
  414. {
  415. return std::unique_ptr<T>(new T());
  416. }
  417. template<typename T, typename Arg1>
  418. std::unique_ptr<T> make_unique(Arg1 &&arg1)
  419. {
  420. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
  421. }
  422. template<typename T, typename Arg1, typename Arg2>
  423. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2)
  424. {
  425. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
  426. }
  427. template<typename T, typename Arg1, typename Arg2, typename Arg3>
  428. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3)
  429. {
  430. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
  431. }
  432. template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  433. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3, Arg4 &&arg4)
  434. {
  435. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
  436. }
  437. #endif
  438. template <typename Container>
  439. typename Container::const_reference circularAt(const Container &r, size_t index)
  440. {
  441. assert(r.size());
  442. index %= r.size();
  443. auto itr = std::begin(r);
  444. std::advance(itr, index);
  445. return *itr;
  446. }
  447. template<typename Range, typename Predicate>
  448. void erase_if(Range &vec, Predicate pred)
  449. {
  450. vec.erase(boost::remove_if(vec, pred),vec.end());
  451. }
  452. template<typename Elem, typename Predicate>
  453. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  454. {
  455. auto itr = setContainer.begin();
  456. auto endItr = setContainer.end();
  457. while(itr != endItr)
  458. {
  459. auto tmpItr = itr++;
  460. if(pred(*tmpItr))
  461. setContainer.erase(tmpItr);
  462. }
  463. }
  464. //works for map and std::map, maybe something else
  465. template<typename Key, typename Val, typename Predicate>
  466. void erase_if(std::map<Key, Val> &container, Predicate pred)
  467. {
  468. auto itr = container.begin();
  469. auto endItr = container.end();
  470. while(itr != endItr)
  471. {
  472. auto tmpItr = itr++;
  473. if(pred(*tmpItr))
  474. container.erase(tmpItr);
  475. }
  476. }
  477. template<typename InputRange, typename OutputIterator, typename Predicate>
  478. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  479. {
  480. return std::copy_if(boost::const_begin(input), std::end(input), result, pred);
  481. }
  482. template <typename Container>
  483. std::insert_iterator<Container> set_inserter(Container &c)
  484. {
  485. return std::inserter(c, c.end());
  486. }
  487. //Returns iterator to the element for which the value of ValueFunction is minimal
  488. template<class ForwardRange, class ValueFunction>
  489. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  490. {
  491. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  492. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  493. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  494. * directly for both function parameters.
  495. */
  496. return boost::min_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  497. {
  498. return vf(lhs) < vf(rhs);
  499. });
  500. }
  501. //Returns iterator to the element for which the value of ValueFunction is maximal
  502. template<class ForwardRange, class ValueFunction>
  503. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  504. {
  505. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  506. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  507. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  508. * directly for both function parameters.
  509. */
  510. return boost::max_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  511. {
  512. return vf(lhs) < vf(rhs);
  513. });
  514. }
  515. template<typename T>
  516. void advance(T &obj, int change)
  517. {
  518. obj = (T)(((int)obj) + change);
  519. }
  520. template <typename Container>
  521. typename Container::value_type backOrNull(const Container &c) //returns last element of container or nullptr if it is empty (to be used with containers of pointers)
  522. {
  523. if(c.size())
  524. return c.back();
  525. else
  526. return typename Container::value_type();
  527. }
  528. template <typename Container>
  529. typename Container::value_type frontOrNull(const Container &c) //returns first element of container or nullptr if it is empty (to be used with containers of pointers)
  530. {
  531. if(c.size())
  532. return c.front();
  533. else
  534. return nullptr;
  535. }
  536. template <typename Container, typename Index>
  537. bool isValidIndex(const Container &c, Index i)
  538. {
  539. return i >= 0 && i < c.size();
  540. }
  541. template <typename Container, typename Index>
  542. boost::optional<typename Container::const_reference> tryAt(const Container &c, Index i)
  543. {
  544. if(isValidIndex(c, i))
  545. {
  546. auto itr = c.begin();
  547. std::advance(itr, i);
  548. return *itr;
  549. }
  550. return boost::none;
  551. }
  552. template <typename Container, typename Pred>
  553. static boost::optional<typename Container::const_reference> tryFindIf(const Container &r, const Pred &t)
  554. {
  555. auto pos = range::find_if(r, t);
  556. if(pos == boost::end(r))
  557. return boost::none;
  558. else
  559. return *pos;
  560. }
  561. template <typename Container>
  562. typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue)
  563. {
  564. if(index < r.size())
  565. return r[index];
  566. return defaultValue;
  567. }
  568. template <typename Container, typename Item>
  569. bool erase_if_present(Container &c, const Item &item)
  570. {
  571. auto i = std::find(c.begin(), c.end(), item);
  572. if (i != c.end())
  573. {
  574. c.erase(i);
  575. return true;
  576. }
  577. return false;
  578. }
  579. template <typename V, typename Item, typename Item2>
  580. bool erase_if_present(std::map<Item,V> & c, const Item2 &item)
  581. {
  582. auto i = c.find(item);
  583. if (i != c.end())
  584. {
  585. c.erase(i);
  586. return true;
  587. }
  588. return false;
  589. }
  590. template <typename Container, typename Pred>
  591. void erase(Container &c, Pred pred)
  592. {
  593. c.erase(boost::remove_if(c, pred), c.end());
  594. }
  595. template<typename T>
  596. void removeDuplicates(std::vector<T> &vec)
  597. {
  598. boost::sort(vec);
  599. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  600. }
  601. template <typename T>
  602. void concatenate(std::vector<T> &dest, const std::vector<T> &src)
  603. {
  604. dest.reserve(dest.size() + src.size());
  605. dest.insert(dest.end(), src.begin(), src.end());
  606. }
  607. template <typename T>
  608. std::vector<T> intersection(std::vector<T> &v1, std::vector<T> &v2)
  609. {
  610. std::vector<T> v3;
  611. std::sort(v1.begin(), v1.end());
  612. std::sort(v2.begin(), v2.end());
  613. std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));
  614. return v3;
  615. }
  616. using boost::math::round;
  617. }
  618. using vstd::operator-=;
  619. using vstd::make_unique;