在我的程序早期,我让程序一次生成一个向量,9个元素。这9组中的每一组都是相关数据。后来我想一次处理每9组(例如每行打印9个)。
我应该怎么做?我的尝试:
for (unsigned int i = 0; i < solutions.size()/9; i++)
{
cout << i << ": " << solutions[0+ i*9] << " " << solutions[1+ i*9] << " " << solutions[2 + i*9] << " " << solutions[3+ i*9] << " " << solutions[4+ i*9] << " " << solutions[5 + i*9] << " " << solutions[6+ i*9] << " " << solutions[7+ i*9] << " "<< solutions[8 + i*9] << endl;
cout << endl;
}
我显然在这里搞砸了。有什么帮助吗?
答案 0 :(得分:3)
我建议使用结构。
struct elems {
elements elems[9];
};
std::ostream& operator<<(std::ostream& out, const elems& elems) {
for(int i = 0; i < 9; i++)
out << elems.elems[i];
return out;
}
std::vector<elems> solutions;
答案 1 :(得分:1)
为什么不使用矢量矢量?
vector< vector <int> > solution;
for (unsigned int i = 0; i < solutions.size(); i++)
{
for(int j=0; j<9; j++) {
cout << solution[i][j] << " ";
}
cout << endl;
}
答案 2 :(得分:0)
简单修复,您只需要一个临时索引变量并在整个循环中递增它,同时每次将主索引增加9。
for(unsigned int i = 0; i < solutions.size(); i += 9) {
int j = i;
std::cout << i << ": " << solutions[j++] << " " << solutions[j++] << " " << solutions[j++] << " " << solutions[j++] << " " << solutions[j++] << " " << solutions[j++] << " " << solutions[j++] << " " << solutions[j++] << " "<< solutions[j++] << std::endl << std::endl;
}