Added getPairs function

This commit is contained in:
Daniel Wolf 2016-05-12 21:21:25 +02:00
parent baf2423b27
commit 9eef09145e
3 changed files with 57 additions and 0 deletions

View File

@ -118,6 +118,7 @@ set(SOURCE_FILES
src/Timed.h
src/TimeRange.cpp src/TimeRange.h
src/Timeline.h
src/pairs.h
src/Exporter.cpp src/Exporter.h
)
add_executable(rhubarb ${SOURCE_FILES})
@ -129,10 +130,12 @@ target_compile_options(rhubarb PUBLIC ${enableWarningsFlags})
set(TEST_FILES
tests/stringToolsTests.cpp
tests/TimelineTests.cpp
tests/pairsTests.cpp
src/stringTools.cpp src/stringTools.h
src/Timeline.h
src/TimeRange.cpp src/TimeRange.h
src/centiseconds.cpp src/centiseconds.h
src/pairs.h
)
add_executable(runTests ${TEST_FILES})
target_link_libraries(runTests gtest gmock gmock_main)

20
src/pairs.h Normal file
View File

@ -0,0 +1,20 @@
#pragma once
#include <vector>
template<typename TCollection>
std::vector<std::pair<typename TCollection::value_type, typename TCollection::value_type>> getPairs(const TCollection& collection) {
using TElement = typename TCollection::value_type;
using TPair = std::pair<TElement, TElement>;
auto begin = collection.begin();
auto end = collection.end();
if (begin == end || ++TCollection::const_iterator(begin) == end) {
return std::vector<TPair>();
}
std::vector<TPair> result;
for (auto first = begin, second = ++TCollection::const_iterator(begin); second != end; ++first, ++second) {
result.push_back(TPair(*first, *second));
}
return result;
}

34
tests/pairsTests.cpp Normal file
View File

@ -0,0 +1,34 @@
#include <gmock/gmock.h>
#include "pairs.h"
using namespace testing;
using std::vector;
using std::initializer_list;
using std::pair;
TEST(getPairs, emptyCollection) {
EXPECT_THAT(getPairs(vector<int>()), IsEmpty());
}
TEST(getPairs, oneElementCollection) {
EXPECT_THAT(getPairs(vector<int>{1}), IsEmpty());
}
TEST(getPairs, validCollection) {
{
auto actual = getPairs(vector<int>{ 1, 2 });
vector<pair<int, int>> expected{ {1, 2} };
EXPECT_THAT(actual, ElementsAreArray(expected));
}
{
auto actual = getPairs(vector<int>{ 1, 2, 3 });
vector<pair<int, int>> expected{ {1, 2}, {2, 3} };
EXPECT_THAT(actual, ElementsAreArray(expected));
}
{
auto actual = getPairs(vector<int>{ 1, 2, 3, 4 });
vector<pair<int, int>> expected{ {1, 2}, {2, 3}, {3, 4} };
EXPECT_THAT(actual, ElementsAreArray(expected));
}
}