Working with vectors

I am new to C++ but not programming.

I am currently working from an old FORTRAN piece of code, which handled vectors in a slightly different manner to C++ (actually, considerably different manner).

Anyway, I have 2 vectors (x and k), both with 4 elements.
I have a value (float at present) h.

I want to do this: h * k
And: x + k/2

I took this approach...

1
2
3
4
for (int i = 0; i < k.size(); i++) {
        k.at(i) = h * k.at(i);
        k.at(i) = x.at(i) + (k.at(i) / 2);
    }


This works but is there a more efficient approach?
What do you perceive as being inefficient?
You have some container of size N, and you are assigning N things. You can't get better than O(n).

If you know x and k are the same size, you can just use k[i] and x[i] instead of using .at() to access each element.
And you can collapse the two statements.

k[i] = x[i] + h * k[i] / 2;

Turning on optimizations usually allows for SIMD instructions to be generated.
Last edited on
Thanks for the shortening of the expression; that helps.

I was curious if someone screamed "no, you should use..."; hence my question.

I noted there was a transform instruction available and, though this did not appear to return greater efficiency through examples I could see online, I did wonder if it would offer neater code (though, I am currently less interested in that - I just want it to work right now). :)

Anyway, thank you for the reply; very much appreciated.
You can use valarray<> instead of vectors.

They will work more like (modern) Fortran arrays and Python's numpy arrays. In particular, you can write "whole-array" statements very simply and not have to use for loops.

For example
1
2
3
4
valarray<double> x(N), k(N);
double h;
//Some code
k = x + h * k / 2;   // Whole-array calculation (which doesn't look correct BTW) 

at is notably slower than [], if no one said. Avoid it unless you can't.

apart from that there is not really anything that will make this code more efficient in terms of execution speed.

there are various things you can do to change how the code looks, such as a range based for loop.
Valarrays are slick but seldom used; they may confuse people that do not use them regularly -- they have some syntax that is unlike everything else in the c++ universe.

doubles are preferred unless you have a reason to use floats.
Last edited on
Thank you lastchance; I will do so immediately. That will make my code far easier to run through.

Yes, Jonnin, I had used the at() because, like a numpty, I had tried to reference the vector element using rounded brackets and the system complained. Even though I had previously realised they needed to be square ones, I proceeded to use the at() statement until Ganado pointed it out to me. All removed now. :)
Registered users can post here. Sign in or register to post.