Problem with for() loops.

I don't understand why this code prints 0 to 24 twice? Thanks for any help.


<code>
#include <iostream>
#include <vector>

int main()
{
vector<float> v;

for(float i = 0.0; i < 25.0; i++)
v.push_back(i);
for(float i = 0.0; i < v.size(); i++)
std::cout << v[i] << " ";
std::cout << std::endl;

for(float j = 0.0; j < 100.0; j += 2.5)
v.push_back(j);
for(float j = 0.0; j < v.size(); j++)
std::cout << v[j] << " ";
std::cout << std::endl;
}

</code>
because you didn't clear the vector from the first run - so it still contains the values inserted during
the first loop.



it's [code] [/code] not <code> </code>
Thanks. That cleared things up. :)
Besides that, vector is in the std namespace... You need to do either using namespace std; or std::vector

Anyways, yeah, use v.clear();
Last edited on
I was in the process of eliminating using namespace std; but missed std::vector until I got the error message"undeclared identifier". Having just googled "clear vector" and implemented the results I mistakenly assumed it had something to do with the new code. I went through v.clear(), v.erase() and v.empty() for about 30 minutes before the nickel finally dropped. Anyway, thanks for the heads up.
Topic archived. No new replies allowed.