Taking sum of std::vector is using references instead of values?
<p>I have a vector containing integer values, which I wish to sum. However, it's summing the total wrong - if the vector holds 10 ints between -10 and 10, my total should not be <code>18446744073709551602</code>. </p>

<p>I declare the vector, and populate it with values:</p>

<pre><code>std::vector&lt;int&gt; X;
for ( int i = 0; i &lt; readings.size() ; ++i ) { 
    X.push_back(readings[i].x);
</code></pre>

<p>I then sum and display:</p>

<pre><code>unsigned long temptotal = 0;
for ( int i = 0; i &lt; readings.size() ; ++i ) {
    std::cout &lt;&lt; "Value in X: " &lt;&lt; X[i] &lt;&lt; std::endl;
    temptotal += X[i];
}
std::cout &lt;&lt; "Temp total: " &lt;&lt; temptotal &lt;&lt; std::endl;
</code></pre>

<p>which produces the following output: <code>Temp total: 18446744073709551603</code>. </p>

<p>When I step through the summation loop in GDB, (at <code>temptotal += X[i];</code>), I can <code>print X[i]</code>: </p>

<pre><code>(gdb) p X[i]
$1 = (reference) @0x100100c80: -1
</code></pre>

<p>Printing <code>temptotal</code> before and after the addition is performed:</p>

<pre><code>(gdb) p temptotal
$2 = 0
(gdb) p temptotal
$3 = 18446744073709551615
</code></pre>

<p>I'm fairly sure that I'm adding the memory locations rather than the values in the memory locations - I could be wrong on that - but I'm not sure why I'm not adding the values at <code>X[i]</code>. When I populate <code>X</code> with the values from <code>readings[i].x</code>, they're <code>double</code>s, which I then type-cast to <code>int</code>s. Is this where my error is? Checking in GDB, my type-cast of the <code>readings[i].x</code> value should be an int, or, at least, a number of some kind:</p>

<pre><code>(gdb) p (int)readings[i].x
$1 = -1
</code></pre>

<p>I'm stumped; if somebody could shed some light on why I'm not adding what I think I'm adding, I'd be grateful. </p>

<p>EDIT<br>
It's the casting from <code>int</code> to <code>unsigned long</code>. I went over it and over it, pressed "submit question" and spotted my error. Although, I still don't understand <strong>why</strong> it's doing what it's doing - any light shed on that would be wonderful - why, if I'm adding an <code>int</code> to an <code>unsigned long</code>, does it not take the value from the <code>int</code>? </p>
