Picking vector elements with a bitset

#include <iostream> #include <vector> #include <bitset> #include <stdexcept> using namespace std; template <typename T, size_t bitset_sz> vector<T> take(const vector<T>& v, const bitset<bitset_sz>& b) { if(v.size() != bitset_sz) { throw length_error("The lengths of the vector and bitset must be the same."); } vector<T> res; for(size_t i = 0; i < v.size(); i++) { if(b[bitset_sz - i - 1]) {res.push_back(v[i]);} } return res; } int main() { vector<string> cities = {"Athens", "Brussels", "Madrid", "Rome", "Bratislava", "Talinn", "Berlin"}; vector<int> nums = {1,2,3,4,5,6,7}; bitset<7> pick_indices("1010001"); for(const string el : take(cities, pick_indices)) { cout << el << " "; } /* Athens Madrid Berlin */ cout << endl; for(const int el : take(nums, pick_indices)) { cout << el << " "; } /* 1 3 7 */ return 0; }

Here bitset_sz - i - 1 ensures that the elements are picked in the order in which the bits are listed. By default b[0] would be the rightmost element in the bitset. This is useful in case we wanted to convert the bit sequence to a number using powers of two (20 + 24 + 26).