Commit 138be05d authored by Davis King's avatar Davis King

Added split_array()

parent 98d7a8bf
......@@ -4,6 +4,7 @@
#define DLIB_ARRAy_
#include "array/array_kernel.h"
#include "array/array_tools.h"
#endif // DLIB_ARRAy_
// Copyright (C) 2013 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_ARRAY_tOOLS_H_
#define DLIB_ARRAY_tOOLS_H_
#include "../assert.h"
#include "array_tools_abstract.h"
namespace dlib
{
template <typename T>
void split_array (
T& a,
T& b,
double frac
)
{
// make sure requires clause is not broken
DLIB_ASSERT(0 <= frac && frac <= 1,
"\t void split_array()"
<< "\n\t frac must be between 0 and 1."
<< "\n\t frac: " << frac
);
const unsigned long asize = static_cast<unsigned long>(a.size()*frac);
const unsigned long bsize = a.size()-asize;
b.resize(bsize);
for (unsigned long i = 0; i < b.size(); ++i)
{
swap(b[i], a[i+asize]);
}
a.resize(asize);
}
}
#endif // DLIB_ARRAY_tOOLS_H_
// Copyright (C) 2013 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#undef DLIB_ARRAY_tOOLS_ABSTRACT_H_
#ifdef DLIB_ARRAY_tOOLS_ABSTRACT_H_
#include "array_kernel_abstract.h"
namespace dlib
{
template <typename T>
void split_array (
T& a,
T& b,
double frac
);
/*!
requires
- 0 <= frac <= 1
- T must be an array type such as dlib::array or std::vector
ensures
- This function takes the elements of a and splits them into two groups. The
first group remains in a and the second group is put into b. The ordering of
elements in a is preserved. In particular, concatenating #a with #b will
reproduce the original contents of a.
- The elements in a are moved around using global swap(). So they must be
swappable, but do not need to be copyable.
- #a.size() == floor(a.size()*frac)
- #b.size() == a.size()-#a.size()
!*/
}
#endif // DLIB_ARRAY_tOOLS_ABSTRACT_H_
......@@ -618,6 +618,25 @@ namespace
DLIB_TEST(dlib::is_array<array<stuff> >::value == true);
}
void test_array_split()
{
array<int> temp(5);
for (unsigned int i = 0; i < temp.size(); ++i)
temp[i] = i;
array<int> b;
split_array(temp, b, 0.5);
DLIB_TEST(temp.size() == 2);
DLIB_TEST(b.size() == 3);
DLIB_TEST(temp[0] == 0);
DLIB_TEST(temp[1] == 1);
DLIB_TEST(b[0] == 2);
DLIB_TEST(b[1] == 3);
DLIB_TEST(b[2] == 4);
}
class array_tester : public tester
{
......@@ -639,6 +658,7 @@ namespace
array_expand_test<array<unsigned long> >();
DLIB_TEST(dlib::is_array<int>::value == false);
test_array_split();
}
} a;
......
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