I have a buch of triangles represented by a vector of 3d vectors ( std::vector<Vector3>
) and indices, represented in the following way
using int3 = std::array<int, 3>;
std::vector<int3> indices;
I need to convert the indices
into a std::vector<size_t>
format to interact with a library.
I know how to do this using raw loops, but I would like to here about how to do it using algorithms. I tried something like
std::vector<size_t> indices_converted;
std::transform(std::begin(indices), std::end(indices), std::back_inserter(indices_converted), [](const auto &v) {
});
but is not enough, since I can't insert three values at once into the indices_converted
vector.
So, what are your ideas?
One-liner using latest version of range-v3 library:
#include <array>
#include <vector>
#include <range/v3/view/join.hpp>
#include <range/v3/range/conversion.hpp>
// ...
std::vector<std::array<int, 3>> v = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
const auto result = ranges::views::join(v) | ranges::to<std::vector>();
You can use either the range-based for loop or the standard algorithm std::for_each
.
For example
#include <iostream>
#include <array>
#include <vector>
#include <iterator>
int main()
{
using int3 = std::array<int, 3>;
std::vector<int3> indices =
{
{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }
};
std::vector<size_t> indices_converted;
indices_converted.reserve( 3 * indices.size() );
for ( const auto &item : indices )
{
indices_converted.insert( std::end( indices_converted ), std::begin( item ), std::end( item ) );
}
for ( const auto &item : indices_converted ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
or
#include <iostream>
#include <array>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
using int3 = std::array<int, 3>;
std::vector<int3> indices =
{
{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }
};
std::vector<size_t> indices_converted;
indices_converted.reserve( 3 * indices.size() );
std::for_each( std::begin( indices ), std::end( indices ),
[&indices_converted]( const auto &item )
{
indices_converted.insert( std::end( indices_converted ), std::begin( item ), std::end( item ) );
} );
for ( const auto &item : indices_converted ) std::cout << item << ' ';
std::cout << '\n';
return 0;
}
In the both cases the output is
1 2 3 4 5 6 7 8 9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.