Add td::contains.

GitOrigin-RevId: 93ce98764505885f5b7218c2f52cedd36fe4533f
This commit is contained in:
levlam 2019-10-22 01:03:39 +03:00
parent 86925625fd
commit 31e8975be5
2 changed files with 30 additions and 1 deletions

View File

@ -102,6 +102,16 @@ void remove_if(T &v, const Func &f) {
v.erase(v.begin() + j, v.end());
}
template <class V, class T>
bool contains(const V &v, const T &elem) {
for (auto &x : v) {
if (x == elem) {
return true;
}
}
return false;
}
template <class T>
void reset_to_empty(T &value) {
using std::swap;

View File

@ -211,7 +211,7 @@ TEST(Misc, base64) {
template <class T>
static void test_remove_if(vector<int> v, const T &func, vector<int> expected) {
remove_if(v, func);
td::remove_if(v, func);
if (expected != v) {
LOG(FATAL) << "Receive " << v << ", expected " << expected << " in remove_if";
}
@ -268,6 +268,25 @@ TEST(Misc, remove_if) {
test_remove_if(v, none, v);
}
TEST(Misc, contains) {
td::vector<int> v{1, 3, 5, 7, 4, 2};
for (int i = -10; i < 20; i++) {
ASSERT_EQ(td::contains(v, i), (1 <= i && i <= 5) || i == 7);
}
v.clear();
ASSERT_TRUE(!td::contains(v, 0));
ASSERT_TRUE(!td::contains(v, 1));
td::string str = "abacaba";
ASSERT_TRUE(!td::contains(str, '0'));
ASSERT_TRUE(!td::contains(str, 0));
ASSERT_TRUE(!td::contains(str, 'd'));
ASSERT_TRUE(td::contains(str, 'a'));
ASSERT_TRUE(td::contains(str, 'b'));
ASSERT_TRUE(td::contains(str, 'c'));
}
TEST(Misc, to_integer) {
ASSERT_EQ(to_integer<int32>("-1234567"), -1234567);
ASSERT_EQ(to_integer<int64>("-1234567"), -1234567);