mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-09-11 05:25:32 +03:00
AK: Add Vector::insert_before_matching(T&&, callback);
This allows you to do things like: vector.insert_before_matching(value, [](auto& entry) { return value < entry; }); Basically it scans until it finds an element that matches the condition callback and then inserts the new value before the matching element.
This commit is contained in:
parent
57da8792fd
commit
55a5c46253
Notes:
sideshowbarker
2024-07-19 13:23:31 +09:00
Author: https://github.com/awesomekling Commit: https://github.com/SerenityOS/serenity/commit/55a5c46253d
@ -132,6 +132,9 @@ public:
|
||||
bool operator==(const String&) const;
|
||||
bool operator!=(const String& other) const { return !(*this == other); }
|
||||
bool operator<(const String&) const;
|
||||
bool operator<(const char*) const;
|
||||
bool operator>=(const String& other) const { return !(*this < other); }
|
||||
bool operator>=(const char* other) const { return !(*this < other); }
|
||||
|
||||
bool operator==(const char* cstring) const
|
||||
{
|
||||
@ -210,6 +213,22 @@ struct Traits<String> : public GenericTraits<String> {
|
||||
static void dump(const String& s) { kprintf("%s", s.characters()); }
|
||||
};
|
||||
|
||||
inline bool operator<(const char* characters, const String& string)
|
||||
{
|
||||
if (!characters)
|
||||
return !string.is_null();
|
||||
|
||||
if (string.is_null())
|
||||
return false;
|
||||
|
||||
return strcmp(characters, string.characters()) < 0;
|
||||
}
|
||||
|
||||
inline bool operator>=(const char* characters, const String& string)
|
||||
{
|
||||
return !(characters < string);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
using AK::String;
|
||||
|
@ -41,5 +41,21 @@ int main()
|
||||
}
|
||||
EXPECT_EQ(loop_counter, 2);
|
||||
|
||||
{
|
||||
Vector<String> strings;
|
||||
strings.append("abc");
|
||||
strings.append("def");
|
||||
strings.append("ghi");
|
||||
|
||||
strings.insert_before_matching("f-g", [](auto& entry) {
|
||||
return "f-g" < entry;
|
||||
});
|
||||
|
||||
EXPECT_EQ(strings[0], "abc");
|
||||
EXPECT_EQ(strings[1], "def");
|
||||
EXPECT_EQ(strings[2], "f-g");
|
||||
EXPECT_EQ(strings[3], "ghi");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
12
AK/Vector.h
12
AK/Vector.h
@ -243,6 +243,18 @@ public:
|
||||
insert(index, T(value));
|
||||
}
|
||||
|
||||
template<typename C>
|
||||
void insert_before_matching(T&& value, C callback)
|
||||
{
|
||||
for (int i = 0; i < size(); ++i) {
|
||||
if (callback(at(i))) {
|
||||
insert(i, move(value));
|
||||
return;
|
||||
}
|
||||
}
|
||||
append(move(value));
|
||||
}
|
||||
|
||||
Vector& operator=(const Vector& other)
|
||||
{
|
||||
if (this != &other) {
|
||||
|
Loading…
Reference in New Issue
Block a user