I’m new with vectors and I am trying to display a vector in a square like you can display a array in a square. Is that possible or do you have to display more than one vector as follows:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>v(3);
vector<int>w(3);
vector<int>x(3);
for(int i = 0; i < 2; i++)
{
v[i] = i;
w[i] = i;
x[i] = i;
cout << v[i] << " " << w[i] << " " << x[i] << endl;
}
return 0;
}
Display:
0 0 0
1 1 1
2 2 2
How do i display one vector in a square? Remember the display is important at this stage and not the values of the vector!!
No, you’re code is not correct. Vectors, like all arrays in C++, are 0-indexed; thus the valid indexes go from
0tosize() - 1. Your code uses indexsize(), and thus has undefined behaviour.Unlike you insist, the values are rather important when you use them as indexes to your vectors. If you simply want to display numbers, you don’t necessarily need any vectors at all (and you can choose your ranges at will):
And no, you don’t need several vectors to display “a square of values”. If you want to output the contents of a single vector to multiple lines, all you got to do is decide how many elements you want to have on a single line, and simply output a newline character after every this many elements, i.e.