I have a function that takes a vector-like input. To simplify things, let's use this print_in_order
function:
#include <iostream>
#include <vector>
template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
vectorlike const & printme) {
for (int i : order)
std::cout << printme[i] << std::endl;
}
int main() {
std::vector<int> printme = {100, 200, 300};
std::vector<int> order = {2,0,1};
print_in_order(order, printme);
}
Now I have a vector<Elem>
and want to print a single integer member, Elem.a
, for each Elem in the vector. I could do this by creating a new vector<int>
(copying a
for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[]
is used on it, returns this only the member a
. Note that I don't want to change the print_in_order
function to access the member, it should remain general.
Is this possible, maybe with a lambda expression? Full code below.
#include <iostream>
#include <vector>
struct Elem {
int a,b;
Elem(int a, int b) : a(a),b(b) {}
};
template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
vectorlike const & printme) {
for (int i : order)
std::cout << printme[i] << std::endl;
}
int main() {
std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
std::vector<int> order = {2,0,1};
// how to do this?
virtual_vector X(printme) // behaves like a std::vector<Elem.a>
print_in_order(order, X);
}
See Question&Answers more detail:os