Given a vector of objects, is there an elegant way to extract its member? I am currently just using a for loop but it would be nice if there is a way to do it. Example:
#include <vector>
struct Object {
int x;
float y;
};
int main() {
std::vector<Object> obj;
// Fill up obj
std::vector<int> all_x = obj.x; // Won't work obviously
}
To extract (also known as indexing or subscripting) one or more values (more generally known as elements) from a vector we use the square bracket [ ] notation.
Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.
Extract value of a single cell: df_name[x, y] , where x is the row number and y is the column number of a data frame called df_name . Extract the entire row: df_name[x, ] , where x is the row number. By not specifying the column number, we automatically choose all the columns for row x .
The c() is a built-in R generic function that combines its arguments. The c() in R is used to create a vector with explicitly providing values. The default method combines its arguments to form a vector. All arguments are coerced to a common type of the returned value, and all attributes except names are removed.
With range-v3, it would simply be
std::vector<int> xs = objs | ranges::view::transform(&Object::x);
or just use the view:
auto xs = objs | ranges::view::transform(&Object::x);
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With