2

I'm pretty new to C++ and I've only used high level languages before.

Here is my question. It's only for trying some things out.

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> ve(10);
    for (unsigned int i; i < ve.size(); i++) {
        ve[i] = i+1;
        cout << ve[i] << endl;
    }
    cout << "Done filling vector. Now showing" << endl;
    for (unsigned int y; y < ve.size(); y++) {
        cout << ve[y] << endl;
    }
    cout << "We're done" << endl;
} 

With the first "for" I want to fill the vector/array with values and output those values.

The second one is supposed to output them all again. However this doesn't happen. the array seems to be empty after the first for is done.

1
  • 1
    In C++ there is no default values. i will contain garbage if you don't initialize it. (Whereas in Java it would have been 0). Commented Dec 14, 2013 at 11:13

3 Answers 3

1

The problem is that you're not initialising the iteration variables, which means they get pretty much random values (whatever happened to lie in memory at their location). Do this instead:

for (unsigned int i = 0; i < ve.size(); i++) {
    ve[i] = i+1;
    cout << ve[i] << endl;
}

and

for (unsigned int y = 0; y < ve.size(); y++) {
    cout << ve[y] << endl;
}

(Note: the difference is the initialisation = 0)


A few unrelated tips:

  • Variables declared in the for loop initialisation clause are local to the loop, they are not accessible outside of it. Which means they could both be called i.

  • std::endl is a combination of "output a newline" and "flush the buffer." Unless you really want both operations, it's preferrable (performance-wise) to just output \n for the newline. E.g.: cout << "We're done.\n";

  • For test programs it's fine, but generally it's advisable not to do using namespace std; even in source files (and it's downright dangerous to do it in header files). It's largely a matter of style, but still sometimes you could be bitten by a name clash.

Sign up to request clarification or add additional context in comments.

Comments

1

You did not initialize variables i and y in the for-loop statements

for (unsigned int i; i < ve.size(); i++) 

Should be

for (unsigned int i = 0; i < ve.size(); i++) 

Comments

1
for (unsigned int i=0; i < ve.size(); i++)

Not

for (unsigned int i; i < ve.size(); i++)

and the same for the printing loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.