I wrote this piece of code, basically, it is a vector of lists. But, I can't see why I'm not able do access the elements that I added into list and its size.
#include "stdafx.h"
#include <list>
#include <vector>
#include <math.h>
#include <cmath>
int _tmain(int argc, _TCHAR* argv[])
{
int n = 4;
std::vector<std::list<int>> S;
int k_max = pow(2,n);
S = std::vector<std::list<int>> (k_max);
for (int k = 1; k <= (k_max-1); k++){
for(int i = 1; i <= n; i++){
if (int(floor(k/pow(2,(i-1))))%2 == 1){
S[k].push_back(i);
S[k].sort();
}
}
}
for (int k = 1; k <= (k_max-1); k++){
for (std::list<int>::iterator it= S[k].begin(); it != --S[k].end(); ++it){
printf("\n%d",*it);
}
//*/
int tam = S[k].size();
getchar();
}
return 0;
}
Also, I can't see any IO header file. I don't know about stdafx.h, does it include IO?
Also, cout is the more C++ way of outputting a simple integer rather than printf().
(sorry for so many Also's)
Also, since you are always sorting the list, IMO you can also use an ordered 'multi-set' rather than a list.
EDIT:
(Another also), there is no need to include <math.h>. It is an old depracted header and <cmath> has all the functionality. You are already including it.
Why are you even using std::list here at all? Considering that you are using it only to store primitive types and you are not utilizing insertion at all, it is a bad choice of container (it is often several orders of magnitude slower than std::vector the way you are using it). std::list has very few specialized use-cases, everywhere else it is the wrong container to use ;)
Really?? Because, I have to create a number of subsets, from a set of integers. So, as I don't know the length of the subset, a list seemed more useful, because for a vector, I would know its size, but, if you have some idea that can help me more, it will be really welcome.
Both a list and a vector can grow and shrink dynamically - C++ vector classes are dynamic arrays, they are not related to the mathematical vector.
As for std::cout vs std::printf, it depends on whether you are using C or C++. In C++, you have access to both, but it is a bad idea to mix and match as you please. Pick one kind of I/O - either stick to C I/O, or stick to C++ I/O. As you are working in C++ I highly recommend using C++ I/O (std::cout, std::cin, etc).
int n, i, u;
n = 8;
i = 0;
u = 4;
vector<list<int>> S;
int k_max = pow(2,n); //máximo de subconjuntos possíveis
S = vector<list<int>> (k_max);
for (int k = 1; k <= (k_max-1); k++){
int i_aux = i;
for(int pos = 1; pos <= n; pos++){
if (int(floor(k/pow(2,(pos-1))))%2 == 1){
S[k].push_back(i_aux);
S[k].sort(); //
i_aux++;
}
else{
i_aux++;
}
}
}
//Printing
for (int k = 1; k <= (k_max-1); k++){
cout << "S[" << k << "] = {" ;
for (list<int>::iterator it = S[k].begin(); it != S[k].end(); ++it){
cout << *it << " ";
}
cout << "}." << endl;
}
Thanks a lot! But I'm not interested in computational time, for while, I only need this subset structure.