I have an data named faces which definition is like this:
struct ivec3 {
unsigned int v0;
unsigned int v1;
unsigned int v2;
};
std::vector<ivec3> faces;
I got the faces with 100 elements(faces.size()=100).
Now I want to get all v0 of faces. If I use the Python, I can do it like this
all_v0 = faces[:, 0]
So, how can I use the slicing operation in C like above code of Python?
Thanks very much!
CodePudding user response:
There is no "slicing operation" for vectors in C .
But this can be done with a simple loop. Or, without writing the loop yourself by using a standard algorithm such as std::transform
.
Consider whether you actually need a new container that has the "slices", or whether you would perhaps be content with having a range that can access those elements. This is analogous to using generator objects instead of creating the list in Python. Example:
auto get_v0 = [](const auto& v) -> auto {
return v.v0;
};
auto v0_range = std::ranges::transform_view(
faces,
get_v0
);
// access the objects:
for (auto v0 : v0_range) {
// use v0
}
// or if you do need a container:
std::vector v0s(begin(v0_range), end(v0_range));
Instead of the function, you can also use a member pointer as demonstrated in 康桓瑋's answer
CodePudding user response:
You can do this with the help of std::transform
:
std::vector<int> all_v0;
all_v0.reserve(faces.size());
std::transform(faces.begin(), faces.end(),
std::back_inserter(all_v0),
[] (const ivec3& i) { return i.v0; });
CodePudding user response:
You can pass in the corresponding member object pointer to C 20 views::transform
to do this.
#include <ranges>
#include <vector>
struct ivec3 {
unsigned int v0;
unsigned int v1;
unsigned int v2;
};
int main() {
std::vector<ivec3> faces;
auto v0s = faces | std::views::transform(&ivec3::v0);
auto v1s = faces | std::views::transform(&ivec3::v1);
auto v2s = faces | std::views::transform(&ivec3::v2);
}