Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to slice the structure vector in c++?

Tags:

c++

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!

like image 531
jack tsang Avatar asked Nov 15 '21 06:11

jack tsang


2 Answers

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; });
like image 133
songyuanyao Avatar answered Sep 18 '22 02:09

songyuanyao


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

like image 26
eerorika Avatar answered Sep 19 '22 02:09

eerorika