If you know how large the vector needs to be, the specify the size in the constructor so that it doesn't need to guess.
vecCoeffs[i];
is a useless statement.
It would be clearer to pull the assignment of starting and ending coefficients out of the loop, and to avoid assigning vecCoeffs[10]
twice. You could assign the starting and ending coefficients in the same statement.
The if-else would be better as a ternary conditional.
vector<double> vecCoeffs(11);
// Starting and ending coefficients
vecCoeffs[0] = vecCoeffs[vecCoeffs.size() - 1] = 1;
// Put the coefficient 2 into each odd index and 4 into each even index
for (int i = 1; i < vecCoeffs.size() - 1; i++) {
vecCoeffs[i] = (i % 2 ? 2 : 4);
}
But the modulo operator is relatively slow. You would be better off with two loops…
vector<double> vecCoeffs(11);
// Starting and ending coefficients
vecCoeffs[0] = vecCoeffs[vecCoeffs.size() - 1] = 1;
for (int i = 1; i < vecCoeffs.size() - 1; i += 2) {
vecCoeffs[i] = 2; // Odd coefficients
}
for (int i = 2; i < vecCoeffs.size() - 1; i += 2) {
vecCoeffs[i] = 4; // Even coefficients
}
… or maybe just one, but getting the termination correct is trickier. This version might eliminate an instruction or two from the loop, but I don't recommend it.
vector<double> vecCoeffs(11);
for (int i = 0; i < vecCoeffs.size() - 1; i += 2) {
vecCoeffs[i] = 4; // Even coefficients
vecCoeffs[i + 1] = 2; // Odd coefficients
}
// Starting and ending coefficients
vecCoeffs[0] = vecCoeffs[vecCoeffs.size() - 1] = 1;
v[0] = 4
and then for each iteration starting ati=1
assignv[i] = 6 - v[i-1]
\$\endgroup\$ – twohundredping Aug 26 '15 at 17:26