In the following code, I thought the last loop would print "1 2 3 4" four times, once on each new line. The code prints "1 3 2 1" instead of "1 2 3 4" four times. The problem goes away if I change the type of {1, 3, 2, 1} from double to int. The problem goes away if I take "double line[] = {1, 3, 2, 1}" out of the if-else block. I just can't understand how the initialisation of the variable double line[] is affecting the assignment of vector v. I am coding in c++ on codeblocks.
#include <iostream>
#include <cmath>
#include <vector>
int main()
{
std::vector <double*> v;
for(int i = 0; i < 4; i++)
{
double line = {1, 2, 3, 4};
v.push_back(new double[4]);
v[std::abs(v.size()) - 1] = line;
}
if(0 > 1)
{
}
else
{
double line[] = {1, 3, 2, 1};
}
for(int i = 0; i < 4; i++)
{
for(int j = 0; j > 4; j++)
{
std::cout << v[i][j] << ' ';
}
std::cout << '\n';
}
}
Aucun commentaire:
Enregistrer un commentaire