Skip to content
Snippets Groups Projects
Commit 3c17020d authored by wenqing's avatar wenqing
Browse files

[Base] Added reorderVector

parent c50dad01
No related branches found
No related tags found
No related merge requests found
/**
* \brief Reorder vector elements by given indices
*
* \copyright
* Copyright (c) 2012-2016, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
* \file reorderVector.h
* Created on October 13, 2016, 5:37 PM
*/
#ifndef OGS_BASELIB_REORDERVECTOR_H
#define OGS_BASELIB_REORDERVECTOR_H
namespace BaseLib
{
/**
* Reorder a vector by a given index vector.
* From
* <a href="reorderV">http://stackoverflow.com/questions/838384/reorder-vector-using-a-vector-of-indices</a>
*
* Note: The simple version on that page is taken, which is good enough in performance
* for medium size vectors.
*/
template <typename ValueType, typename IndexType>
void reorderVector(std::vector<ValueType>& v,
std::vector<IndexType> const& order)
{
for (std::size_t s = 1, d; s < order.size(); ++s)
{
for (d = order[s]; d < s; d = order[d]);
if (d == s)
while (d = order[d], d != s)
std::swap(v[s], v[d]);
}
}
} // end of namespace
#endif /* OGS_BASELIB_REORDERVECTOR_H */
/**
* \copyright
* Copyright (c) 2012-2016, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
* \file TestreorderVector.cpp
*
* Created on August 14, 2016, 10:01 AM
*
*/
#include <vector>
#include <gtest/gtest.h>
#include "BaseLib/reorderVector.h"
TEST(BaseLib_reorderVector, testreorderVector)
{
std::vector<double> vec {2016.0, 1996.0, 2006.0, 1986.0};
std::vector<int> order {3, 1, 2, 0};
BaseLib::reorderVector(vec, order);
EXPECT_EQ(1986.0, vec[0]);
EXPECT_EQ(1996.0, vec[1]);
EXPECT_EQ(2006.0, vec[2]);
EXPECT_EQ(2016.0, vec[3]);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment