Skip to content

Commit

Permalink
ENH: Add itk::MakeVectorContainer(std::vector<TElement>)
Browse files Browse the repository at this point in the history
Eases making an `itk::VectorContainer` based on a specific `std::vector` instance.
  • Loading branch information
N-Dekker authored and dzenanz committed Sep 20, 2024
1 parent 0b03a81 commit 08ff78c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Modules/Core/Common/include/itkVectorContainer.h
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,18 @@ class ITK_TEMPLATE_EXPORT VectorContainer
, VectorType(first, last)
{}
};


/** Makes a VectorContainer that has a copy of the specified `std::vector`. */
template <typename TElement>
auto
MakeVectorContainer(std::vector<TElement> stdVector)
{
auto vectorContainer = VectorContainer<SizeValueType, TElement>::New();
vectorContainer->CastToSTLContainer() = std::move(stdVector);
return vectorContainer;
}

} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
Expand Down
35 changes: 35 additions & 0 deletions Modules/Core/Common/test/itkVectorContainerGTest.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,38 @@ TEST(VectorContainer, HasValueOfCreatedElementAtIdentifier)
ExpectContainerHasValueOfCreatedElementAtIdentifier(magicIdentifier, i);
}
}


// Tests MakeVectorContainer.
TEST(VectorContainer, Make)
{
const auto checkCopy = [](const auto & stdVector) {
const auto vectorContainer = itk::MakeVectorContainer(stdVector);
ASSERT_NE(vectorContainer, nullptr);
EXPECT_EQ(vectorContainer->CastToSTLConstContainer(), stdVector);
};

const auto checkMove = [](auto stdVector) {
const auto * const originalData = stdVector.data();
const auto vectorContainer = itk::MakeVectorContainer(std::move(stdVector));

// After the "move", the vectorContainer should hold the original data pointer.
ASSERT_NE(vectorContainer, nullptr);
EXPECT_EQ(vectorContainer->CastToSTLConstContainer().data(), originalData);
};

checkCopy(std::vector<int>());
checkCopy(std::vector<int>{ 0, 1 });
checkCopy(std::vector<double>());
checkCopy(std::vector<double>{ std::numeric_limits<double>::lowest(),
std::numeric_limits<double>::denorm_min(),
std::numeric_limits<double>::min(),
std::numeric_limits<double>::epsilon(),
std::numeric_limits<double>::max() });

for (const unsigned int numberOfElements : { 1, 2 })
{
checkMove(std::vector<int>(numberOfElements));
checkMove(std::vector<double>(numberOfElements));
}
}

0 comments on commit 08ff78c

Please sign in to comment.