Making at work for container with not random access iterators

This commit is contained in:
AntonBikineev 2015-09-29 17:57:33 +03:00
parent d023ad51a7
commit 65462e6dcd
2 changed files with 18 additions and 1 deletions

View File

@ -89,7 +89,13 @@ template <class T, size_t N>
T& at(std::array<T, N>& arr, size_t index) { fail_fast_assert(index < N); return arr[index]; } T& at(std::array<T, N>& arr, size_t index) { fail_fast_assert(index < N); return arr[index]; }
template <class Cont> template <class Cont>
typename Cont::value_type& at(Cont& cont, size_t index) { fail_fast_assert(index < cont.size()); return cont[index]; } typename Cont::value_type& at(Cont& cont, size_t index)
{
fail_fast_assert(index < cont.size());
auto it = cont.begin();
std::advance(it, index);
return *it;
}
// //

View File

@ -17,6 +17,7 @@
#include <UnitTest++/UnitTest++.h> #include <UnitTest++/UnitTest++.h>
#include <gsl.h> #include <gsl.h>
#include <vector> #include <vector>
#include <list>
using namespace std; using namespace std;
using namespace Guide; using namespace Guide;
@ -52,6 +53,16 @@ SUITE(at_tests)
CHECK_THROW(at(a, 4), fail_fast); CHECK_THROW(at(a, 4), fail_fast);
} }
TEST(StdList)
{
std::list<int> a = { 1, 2, 3, 4 };
for (int i = 0; i < 4; ++i)
CHECK(at(a, i) == i+1);
CHECK_THROW(at(a, 4), fail_fast);
}
} }
int main(int, const char *[]) int main(int, const char *[])