Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract elements from a vector of object

Tags:

c++

vector

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
}
like image 674
Kong Avatar asked Oct 04 '16 04:10

Kong


People also ask

How do you extract an element from a vector?

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.

How do I extract elements from a vector in R?

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.

How do I extract specific values in R?

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 .

What is c () R?

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.


1 Answers

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

like image 178
Jarod42 Avatar answered Nov 15 '22 08:11

Jarod42