Line data Source code
1 : /**
2 : * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
3 : * http://soramitsu.co.jp
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 :
18 : #ifndef IROHA_SET_HPP
19 : #define IROHA_SET_HPP
20 :
21 : #include <unordered_set>
22 :
23 : namespace iroha {
24 : /**
25 : * Merge collections with unique elements
26 : * @tparam Collection - type of collection
27 : * @tparam TargetType - type of elements in collection
28 : * @tparam Hasher - class for hashing TargetType objects
29 : * @param left - first collection
30 : * @param right - second collection
31 : * @return collection with type Collection, that contain unique union of elements
32 : */
33 : template<typename Hasher,
34 : typename Collection,
35 : typename TargetType = typename Collection::value_type>
36 : auto merge_unique(Collection left, Collection right) {
37 : std::unordered_set<TargetType, Hasher>
38 : unique_set(left.begin(), left.end());
39 :
40 : unique_set.insert(right.begin(), right.end());
41 : return Collection(unique_set.begin(), unique_set.end());
42 : }
43 :
44 : /**
45 : * Provide merge of sets based on mering same elements
46 : * @tparam Set - type of set
47 : * @tparam Merge - type of merge predicate
48 : * @param left - first set
49 : * @param right - second set
50 : * @param merge - merge predicate
51 : * @return new set, that contains union of elements,
52 : * where same elements merged inside
53 : */
54 : template<typename Set, typename Merge>
55 : Set set_union(const Set &left, const Set &right, Merge &&merge) {
56 : Set out;
57 : out.insert(left.begin(), left.end());
58 : for (auto &&tx : right) {
59 : auto iter = out.find(tx);
60 : if (iter != out.end()) {
61 : merge(*iter, tx);
62 : } else {
63 : out.insert(tx);
64 : }
65 : }
66 : return out;
67 : }
68 :
69 : /**
70 : * Provide difference operation on set
71 : * @tparam Set - type of set
72 : * @return difference of sets.
73 : */
74 : template<typename Set>
75 : Set set_difference(const Set &left, const Set &right) {
76 25 : Set out;
77 46 : for (auto &&element : left) {
78 21 : if (right.find(element) == right.end()) {
79 19 : out.insert(element);
80 19 : }
81 : }
82 25 : return out;
83 25 : }
84 : } // namespace iroha
85 : #endif //IROHA_SET_HPP
|