Verified Commit 16ed4772 authored by nagayama15's avatar nagayama15

add safe_unique()

parent 99cbfb41
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
#include <algorithm> #include <algorithm>
#include "BitStreamWriter.hpp" #include "BitStreamWriter.hpp"
#include "CircularBitStreamReader.hpp" #include "CircularBitStreamReader.hpp"
#include "SafeUnique.hpp"
namespace kyut { namespace kyut {
namespace detail { namespace detail {
......
#ifndef INCLUDE_kyut_SafeUnique_cpp
#define INCLUDE_kyut_SafeUnique_cpp
#include <cassert>
#include <vector>
namespace kyut {
template <typename Iterator, typename Pred>
Iterator safe_unique(Iterator begin, Iterator end, Pred pred) {
if (begin == end) {
return begin;
}
// This implementation is inefficient
std::vector<typename std::iterator_traits<Iterator>::value_type> a, b;
auto it = begin;
a.emplace_back(std::move(*it++));
while (it != end) {
if (pred(a.back(), *it)) {
b.emplace_back(std::move(*it));
} else {
a.emplace_back(std::move(*it));
}
++it;
}
it = begin;
for (std::size_t i = 0; i < a.size(); i++) {
*it++ = std::move(a[i]);
}
const auto result = it;
for (std::size_t i = 0; i < b.size(); i++) {
*it++ = std::move(b[i]);
}
assert(it == end);
return result;
}
} // namespace kyut
#endif // INCLUDE_kyut_SafeUnique_cpp
...@@ -4,6 +4,7 @@ add_executable(test_kyut ...@@ -4,6 +4,7 @@ add_executable(test_kyut
test_BitStreamWriter.cpp test_BitStreamWriter.cpp
test_CircularBitStreamReader.cpp test_CircularBitStreamReader.cpp
test_Reordering.cpp test_Reordering.cpp
test_SafeUnique.cpp
) )
target_link_libraries(test_kyut target_link_libraries(test_kyut
......
#include "kyut/SafeUnique.hpp"
#include <string>
#include <gtest/gtest.h>
TEST(kyut, safe_unique) {
std::string x = "01122233458889";
const auto result = kyut::safe_unique(std::begin(x), std::end(x), [](char a, char b) { return a == b; });
EXPECT_EQ(result, std::begin(x) + 8);
EXPECT_EQ(x, "01234589122388");
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment