blob: f672f998d9303b9bd27a4ef134cb8a5430597108 [file] [log] [blame]
Vishnu Nairdc4d31b2022-11-17 03:20:58 +00001/*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <vector>
20
21namespace android::surfaceflinger::frontend {
22// Erases the first element in vec that matches value. This is a more optimal way to
23// remove an element from a vector that avoids relocating all the elements after the one
24// that is erased.
25template <typename T>
26void swapErase(std::vector<T>& vec, const T& value) {
27 auto it = std::find(vec.begin(), vec.end(), value);
28 if (it != vec.end()) {
29 std::iter_swap(it, vec.end() - 1);
30 vec.erase(vec.end() - 1);
31 }
32}
33
34// Similar to swapErase(std::vector<T>& vec, const T& value) but erases the first element
35// that returns true for predicate.
36template <typename T, class P>
37void swapErase(std::vector<T>& vec, P predicate) {
38 auto it = std::find_if(vec.begin(), vec.end(), predicate);
39 if (it != vec.end()) {
40 std::iter_swap(it, vec.end() - 1);
41 vec.erase(vec.end() - 1);
42 }
43}
44
45} // namespace android::surfaceflinger::frontend