diff --git a/Modules/Core/Common/include/itkVectorContainer.h b/Modules/Core/Common/include/itkVectorContainer.h index 051ef30cd3c..e32462d8458 100644 --- a/Modules/Core/Common/include/itkVectorContainer.h +++ b/Modules/Core/Common/include/itkVectorContainer.h @@ -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 +auto +MakeVectorContainer(std::vector stdVector) +{ + auto vectorContainer = VectorContainer::New(); + vectorContainer->CastToSTLContainer() = std::move(stdVector); + return vectorContainer; +} + } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Modules/Core/Common/test/itkVectorContainerGTest.cxx b/Modules/Core/Common/test/itkVectorContainerGTest.cxx index 775e709b4e0..90b311b728c 100644 --- a/Modules/Core/Common/test/itkVectorContainerGTest.cxx +++ b/Modules/Core/Common/test/itkVectorContainerGTest.cxx @@ -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()); + checkCopy(std::vector{ 0, 1 }); + checkCopy(std::vector()); + checkCopy(std::vector{ std::numeric_limits::lowest(), + std::numeric_limits::denorm_min(), + std::numeric_limits::min(), + std::numeric_limits::epsilon(), + std::numeric_limits::max() }); + + for (const unsigned int numberOfElements : { 1, 2 }) + { + checkMove(std::vector(numberOfElements)); + checkMove(std::vector(numberOfElements)); + } +}