# Create a subvector containing specific elements of a vector

Suppose a vector with values ​​[0,1,2,3,4,5,6,7,8,9]. How can I create a vector that references optionally adjacent values, eg. [3,4,7,9], that is, given by some index, using STL.

+3

source to share

You can express this as a transformation, for example:

``````#include <valarray>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>

template <typename T>
void pick(std::vector<T>& result, const std::vector<T>& in, const std::vector<typename std::vector<T>::size_type>& s) {
result.reserve(s.size());
std::transform(s.begin(), s.end(), std::back_inserter(result),
[&in](typename std::vector<T>::size_type idx) {
return in.at(idx);
});
}

int main() {
const std::vector<int> arr={0,1,2,3,4,5,6,7,8,9,10};
std::vector<int> result;
pick(result, arr, {3,4,7,9});
}
```

```

I used lambda, but you can also use `std::bind`

or (now deprecated) `std::bind2nd`

for this.

The C ++ 11 example `std::bind`

does `pick`

:

``````template <typename T>
void pick(std::vector<T>& result, const std::vector<T>& in, const std::vector<typename std::vector<T>::size_type>& s) {
result.reserve(s.size());
std::transform(s.begin(), s.end(), std::back_inserter(result),
std::bind(static_cast<const T& (std::vector<T>::*)(typename std::vector<T>::size_type) const>(&std::vector<T>::at),  in, std::placeholders::_1));
}
```

```

This is seriously ugly, though due to the need to discard the member function pointer to resolve overload `at`

(const vs non-const versions).

+3

source

All Articles