I've been coding C for almost 20 years and figured I should learn C++. As a starting point I wrote the following trivial code to generate the powerset of a set. I'm hoping that some experienced C++ coder could help me with three things:
Identify non-idiomatic constructions.
Explain where I'm doing unnecessary copying of objects
Any other simplifying comments.
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
vector<vector<T>> powerset(vector<T> s)
{
// Return the powerset containing the empty set
if(s.size() == 0) {
vector<int> dummy;
return vector<vector<T>> { dummy };
}
T v = s.back();
s.pop_back();
// Recursively generate powerset for s setminus v
vector<vector<T>> pss = powerset<T>(s);
// This is the basis for the current powerset set
vector<vector<T>> ps = pss;
for(auto&& i : pss) {
// Add a set with v added for each set
i.push_back(v);
ps.push_back(i);
}
return ps;
}
int main(void)
{
vector<int> v = {1,2,3,4};
vector<vector<int>> ps = powerset<int>(v);
cout << "Powerset contains the following elements:" << endl;
for(auto&& i : ps) {
for(auto&& j : i) {
cout << j << " ";
}
cout << endl;
}
return 0;
}
void
in the declaration of parameter-less functions. C++ does not requires it, so it is just code clutter. E.g.:int main()
instead ofint main(void)
. \$\endgroup\$