Vector in a for loop, is confusing me.

This is a discussion on Vector in a for loop, is confusing me. within the C++ Programming forums, part of the General Programming Boards category; Hello, I'm an aspiring c++ coder, I'm using two books:"Learning to Program in C++" By Steve Heller, ISBN: 0-13-032410-8 ; ...

  1. #1
    dreamerv3
    Guest

    Vector in a for loop, is confusing me.

    Hello, I'm an aspiring c++ coder, I'm using two books:"Learning to Program in C++" By Steve Heller, ISBN: 0-13-032410-8 ; And "C++: The Complete Reference Third Edition" By Herbert Schildt.

    I usually lurk and just absorb the discussions around here, however I've gotten to a point in my studies where I have a question and this board seems to be a great place to ask it.

    Ok so I'm up to vectors in the first book pp,159.
    And I'm a bit confused. Here is the code snippet and my questions.

    ************************************************** *****************************************

    vector<short> Weight(5);
    vector<short> SortedWeight(3);
    short HighestWeight;
    short HighestIndex;
    short i;
    short k;

    So far I understand perfectly.


    cout << "I'm going to ask you to type in five weights, in pounds." << endl;

    for (i = 0; i < 5; i ++)
    {
    cout << "Please type in weight #" << i+1 << ": ";

    1.)
    Ok I understand what he's doing by using i+1 to make the weight number on the prompt increment each time
    through, however doesn't this expression change the value of i and there fore screw up the for loop
    conditional statement?

    cin >> Weight[i];

    2.)
    Ok, this part confuses me, Are we putting the value into the variable i? and if so won't it screw up the conditional statement of the for loop? Whats going on here? How can the i in the for loop, the i in the
    cout expression and the [i] in the Weight index variable not become corrupted with constant value
    changes, as there are different processes at work independantly in the for loop condition, the cout
    expression, and the vector Weight?

    Does The [i] in Weight simply mean "Process or deal with this index as a list?" So if I entered 5 values
    into Weight would they be stored in each of the five elements which where declared on each respective
    turn through the for loop? And if so why not just say "cin >> Weight;"? Why the [i]? and why i?
    why not [weight] or [w]?

    }

    ************************************************** *****************************************

    Thanks a lot for your time, I really appreciate this.

    Dreamerv3@mail.com

  2. #2
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    >> i+1

    No, this doesn't increment i. It incriments a temp value which is displayed through cout. Incrimenting it would be:
    Code:
    i+=1;
    >> cin >> Weight[i];

    No, this isn't putting a variable into i, it's putting a variable into the vector Weight at index i (a vector is basically an array), so this is the same as:

    Code:
    short Weight[5];
    Weight[0]=12;
    Weight[1]=29;
    etc. etc. etc.
    Hope this helps.

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    1.)
    Ok I understand what he's doing by using i+1 to make the weight number on the prompt increment each time
    through, however doesn't this expression change the value of i and there fore screw up the for loop
    conditional statement?

    cin >> Weight[i];
    Quick answer, no. The FOR loop does the actual incrementing. You're simply using the current 'i' value (plus 1) to display a value. 'i' remains unchanged.

    Second question: Whoa! Lot's of stuff here!

    First, understand that a vector is a 'container', just as a simple array is a 'container'. The difference is that the STL (Standard Template Library) provides, above all, memory management for a vector that is not provided for a simple array. A 'vector' will expand and collapse as it's size is changed, i.e. size is changed as elements are added and deleted. (Not always true, but close enough.) As you are probably aware, a simple array can't do this.

    'i' is an index. It provides a reference, in the computer's memory, for locating the specific data contained within the vector. In essence, it behaves like a pointer. Same mechanism.

    From within your FOR loop, 'i' is given a value. If your code doesn't invoke the assignment operator (=) upon that value, there isn't any change made to the current value of 'i'. Do what you want with it (short of an 'assignment') and it remains the same.

    Now (the "good" part?), a vector, like an array, is initially assigned a section of contiguous memory. Each subsection of that 'chunk' of memory is based on the "size" of the data read into it. (Read up on sizeof().)

    Each subsection (index) is allocated a specific amount of memory (in bytes). When you access the index, you are going to a specific memory location within the memory set aside for the vector (array). That's how arrays, and vectors, work.

    (I'm chasing jdinger tonight, but look at what's provided. jdinger has provided the Reader's Digest version and I've provided the War and Peace version.)

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  4. #4
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Originally posted by skipper
    (I'm chasing jdinger tonight, but look at what's provided. jdinger has provided the Reader's Digest version and I've provided the War and Peace version.)
    -Skipper
    Cut me some slack, Skip! It's been a long day at work coding custom export routines for Access databases. (off topic, I HATE coding in VBA).

    About all I can handle tonight is quick and to the point answers. Any more than that without some rest and my brain might shut down. I'm treading lightly to stay concious.

  5. #5
    dreamerv3
    Guest
    jdinger and skipper:

    //>> cin >> Weight[i];

    //No, this isn't putting a variable into i, it's //putting a variable into the vector Weight at //index i

    So does this mean I can do this:

    vector<short>Weight(5);

    for(whatever)
    {
    cin >> Weight[a];
    }
    for(whatever)
    {
    cin >> Weight[b];
    }
    for(whatever)
    {
    cin >> Weight[c];
    }

    And each Index letter ie: a,b,c can have its own set of up to five values or do I need to declare and index latter as variables first?

    ie:

    short a;
    short b;
    short c;

    I think I'm beginning to understand, however do I need to declare the variables first? this seems irrelevant since from what you're saying it appears the index letters are NOT the variables I declared up top, but simply letters to refer to an index of 5 values.

    And the i+1 in the cout statement: cout << "Please type in weight #" << i+1 << ": ";

    Is a temporary value which doesn't affect the short i?

    So if I do:

    short i = 21;

    then:

    cout << "Please type in weight #" << i+1 << ": ";

    The value of the short i does not become 22?

    Ok if thats true I got it down.

    Also, why does the vector Weight even need a letter to refer to it? is this so that I can have multiple indexes named Weight, yet under different refernce letters? ie: a,b,c?

    And if so how many reference letters, numbers or symbols can I have for a vector?

    32768?
    65536?

    This is very interesting, it sucks that they don't cover important stuff like this in most books.

  6. #6
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    jdinger,

    Then, what, in the name of all that's holy, are you doing out here?

    Get some rest!

    -Skipper
    Last edited by skipper; 08-09-2002 at 08:15 PM.
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  7. #7
    dreamerv3
    Guest
    Are you talking to me?

  8. #8
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    No, dreamerv3.

    Sorry.

    Still studying your question, although your subscripts need to be int's, not char's.

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  9. #9
    dreamerv3
    Guest
    ints as in:

    Vector<short>Weight(5);

    Weight[0]
    Weight[1]
    Weight[2]
    Weight[3]
    Weight[4]

    etc?

  10. #10
    Registered User
    Join Date
    Jan 2002
    Posts
    18
    Sorry it didn't let me edit the message.

    I though referring to vectors like:
    Code:
    vector<short>Weight(5);
    
    for(i = 0, i<5, i++)
    {
    cin>> Weight;
    }
    Would make more sense than the example in my book which says:
    Code:
    vector<short>Weight(5);
    Short i;
    
    for(i = 0, i<5, i++)
    {
    cin>> Weight[i];
    }
    That part threw me off. Why would I need two variable declarations to use A single variable Weight.

    Anyhow thats the example it gave me more specifically here is the example right off the CD:
    Code:
    #include <iostream.h>
    #include "vector.h"
    
    int main()
    {
        vector<short> Weight(5);
        vector<short> SortedWeight(3);
        short HighestWeight;
        short HighestIndex;
        short i;
        short k;
    
        cout << "I'm going to ask you to type in five weights, in pounds." << endl;
    
        for (i = 0; i < 5; i ++)
          {
          cout << "Please type in weight #" << i+1 << ": ";
          cin >> Weight[i];
          }
    
        for (i = 0; i < 3; i ++)
            {
            HighestWeight = 0;
            for (k = 0; k < 5; k ++)
                {
                if (Weight[k] > HighestWeight)
                    {
                    HighestWeight = Weight[k];
                    HighestIndex = k;
                    }
                }
            SortedWeight[i] = HighestWeight;
            Weight[HighestIndex] = 0;
            }
    
        cout << "The highest weight was: " << SortedWeight[0] << endl;
        cout << "The second highest weight was: " << SortedWeight[1] << endl;
        cout << "The third highest weight was: " << SortedWeight[2] << endl;
    
        return 0;
    }
    I know the headers need to be modified for it to compile on most compilers hwever this was written with DJGPP in mind, I'm running Linux so I use GCC 3.x, which is the C++ compiler with the latest additions to the spec.
    most console dos apps in the book compile fine on my system. But thats irrelevant.

    The point is this example compiles fine and runs on my system, so the author must be doing things right. He's got chars for his subscripts and all sorts of things that tend to confuse me. Buts it good because I get to find things like this out that are never mentioned in the book...

    So anyway to recap, my question now is:

    Can I do this?:
    Code:
    vector<short>Weight(5);
    
    for(whatever)
    {
    cin >> Weight[a];
    }
    for(whatever)
    {
    cin >> Weight[b];
    }
    for(whatever)
    {
    cin >> Weight[c];
    }
    And each Index letter ie: a,b,c can have its own set of up to five values or do I need to declare an index subscript letter as variables first?

    ie:

    short a;
    short b;
    short c;

    I think I'm beginning to understand, however do I need to declare the variables first? this seems irrelevant since from what you're saying it appears the index letters are NOT the variables I declared up top, but simply letters to refer to an index of 5 values.

    And the i+1 in the cout statement:
    cout << "Please type in weight #" << i+1 << ": ";

    Is a temporary value which doesn't affect the short i?

    So if I do:

    short i = 21;

    then:

    cout << "Please type in weight #" << i+1 << ": ";

    The value of the short i does not become 22?

    IF THIS IS ALL TRUE then I got it.
    Last edited by Dreamerv3; 08-09-2002 at 10:55 PM.

  11. #11
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    Dreamerv3,

    (It's a little early, so, please, bear with me...)

    vector<short>Weight(5);
    This allocates enough memory in the vector of five 'shorts'. (While a vector isn't, generally, hampered by memory constraints, there are times when it's advisable to set aside a specific amount of memory for a vector to avoid the overhead (time) of forcing the compiler to relocate the array to a different area on the 'free store'.)

    'i' must be declared, regardless. In the FOR loop statement, 'i' serves merely as a counter, however, because 'i' is a variable, it must be declared with a type just as any other variable must be.

    To this point, 'i' and Weight(5) are, as yet, unrelated to one another. Apples and oranges, if you will.

    To your primary question, I've never seen alpha characters used as array subscripts in place of numerals. Can this even be done? Yes.

    Code:
    enum sub {a, b, c, d, ..., z};
    As you may already be aware, the 'enum' statement creates user-defined types of these char's. The compiler will evaluate 'a' as 0, 'b' as 1, 'c' as 2, ..., 'z' as 25.

    Now, would I recommend doing such a thing. Oh, Lord, no! Offhand, I'd be afraid to see what would happen!

    Could you also do this?:
    Code:
    short a[5];
    short b[5];
    short c[5];
    Yes, you could. This begs the question of whether, or not, however, you could then compile
    Code:
    cin >> Weight[a[i]];  // where i = 0 to 4 (your five additional values)
    Seems possible, but compilers are funny animals.

    Last question, (I think). In the 'cout' statement, you can manipulate 'i' by adding one, subtracting two, multiplying by three, whatever. You just can't reassign the value if you want the loop to remain intact.

    That being said, an old BASIC trick, while searching an array sequentially, was to reassign the counter value to an arbitrarily high number within the FOR loop to force it to break out of the loop when a comparison evaluated to 'true'. Much along the lines of using 'break;' in C++ and accomplishing the same thing.

    Code:
    cout << "I'm going to ask you to type in five weights, in pounds." << endl;
    
        for (i = 0; i < 5; i ++)
          {
          cout << "Please type in weight #" << i+21 << ": ";
          cin >> Weight[i];
          }
    This displays, "Please type in weight #22:". 'i' remains whatever value it was.

    Code:
    cout << "I'm going to ask you to type in five weights, in pounds." << endl;
    
        for (i = 0; i < 5; i ++)
          {
          cout << "Please type in weight #" << i+1 << ": ";
          cin >> Weight[i];
          i = 21;  //  'i' now equals 21 and your loop is kaput!
          }
    This will display, "Please type in weight #1:", and then reassigns 'i' the value of 21. The test in your FOR will fail and the loop will end.

    Whew...

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

  12. #12
    Registered User
    Join Date
    Jan 2002
    Posts
    18
    Thanks, That was really helpful.

    And I'm sorry for seeming like an idiot, the book I'm using just does eccentric examples like this and I think it would be wiser to switch, to a book with more standard code examples.

    Anyhow, so I'm going to go off to the compiler and test all this out, but I might as well ask you.

    Should I be doing this:

    Code:
    cout << "I'm going to ask you to type in five weights, in pounds." << endl;
    
        for (i = 0; i < 5; i ++)
          {
          cout << "Please type in weight #" << i+1 << ": ";
          cin >> Weight;
          }
    Rather than this:
    Code:
    cout << "I'm going to ask you to type in five weights, in pounds." << endl;
    
        for (i = 0; i < 5; i ++)
          {
          cout << "Please type in weight #" << i+1 << ": ";
          cin >> Weight[i];
          }
    Since you said:

    " To your primary question, I've never seen alpha characters used as array subscripts in place of numerals. Can this even be done? Yes. "
    "Now, would I recommend doing such a thing. Oh, Lord, no! Offhand, I'd be afraid to see what would happen!"

    Thats the last of it I swear.

    And thanks a again.

  13. #13
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Originally posted by Dreamerv3
    I think it would be wiser to switch, to a book with more standard code examples.
    What would be a more standard than the STL?

    Should I be doing this:

    Code:
    cout << "I'm going to ask you to type in five weights, in pounds." << endl;
    
        for (i = 0; i < 5; i ++)
          {
          cout << "Please type in weight #" << i+1 << ": ";
          cin >> Weight;
          }
    No, you shouldn't. Doing it the way you've coded above will change the value of Weight each iteration of the loop (at least, as long as the user inputs something different from the last iteration).

    In your example above you have a single variable called Weight. This can only hold one weight value.

    With a vector you can hold more than one weight value (as in your original code example where you can hold the values of 5 different weights).

    vector<short> Weight(5) is a container to hold 5 integer values called Weight, which can be individually accessed per their individual indexs.
    ie:
    Code:
    short Temp=150;
    
    //you could do
    short Weight1;
    short Weight2;
    short Weight3;
    short Weight4;
    short Weight5;
    
    Weight1=Temp;
    
    //or you could use
    vector<short> Weight(5);
    Weight.push_back(Temp);

  14. #14
    Registered User
    Join Date
    Jan 2002
    Posts
    18
    Alright, I just checked my second book, and it too uses subscripts to refer to index variables.

    Things like
    Code:
    for (i = 0, i < 5, i++)
    {
    Weight[i] = i;
    }
    Would populate Weight with 0,1,2,3,4
    at each respective element:
    Code:
    Weight[1] //would be 0
    Weight[2] //would be 1
    Weight[3] //would be 2
    etc

    Does the use of [i] tell the compiler to fill the index in order from element 1 onwards?

    And is [i[ arbitrary? so could I just as easily use [x] [y] [z]?

    Would I have to declare them before hand as in:

    short i; //for Weight[i]

    short x; //for Weight[x]
    short y; //for Weight[y]
    short z; //for Weight[z]

    to be able to write the following:

    Code:
    for (i = 0, i < 5, i++)
    {
    Weight[i] = i; //Or [x] or [y] or [z] ?
    }
    Again I apologize for the seemingly redundant questions.


    I just need to nail this part down before I proceed.

  15. #15
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    First, I couldn't agree with jdinger more! Study the STL until it's coming out of your ears. I fully appreciate the concept of learning the "foundation" ideas and processes, but, in this instance, go for vectors over arrays. (Even Mr. Stroustrup advises this...and much more!)

    Does the use of [i] tell the compiler to fill the index in order from element 1 onwards?
    First element, yes, but with a subscript of 0. Your code is good where (i+1) is concerned in the 'cout' statement. This makes it readable and understandable to the user. You as the programmer must keep the details in mind, i.e. first element is the zero index.



    And is [i[ arbitrary? so could I just as easily use [x] [y] [z]?
    Absolutely arbitrary. Doesn't even need to be a single char variable. Give it a name like 'forCntr' if that's your preference.
    Would I have to declare them before hand as in:

    short i; //for Weight[i]

    short x; //for Weight[x]
    short y; //for Weight[y]
    short z; //for Weight[z]
    No. In fact, the general rule of thumb is to declare/define a variable as close to the code in which it is used as is practicable. In your case, within the FOR statement itself is excellent.

    Code:
    for (short x = 0; x < 5; x++)
    {
    // whatever stuff goes here
    }
    Again I apologize for the seemingly redundant questions.
    Very considerate, but unnecessary.

    -Skipper
    "When the only tool you own is a hammer, every problem begins to resemble a nail." Abraham Maslow

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf is confusing me.
    By babelosopher in forum C Programming
    Replies: 10
    Last Post: 07-12-2007, 04:22 PM
  2. Most confusing language
    By Suchy in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 04-22-2007, 09:08 PM
  3. confusing error messages?
    By ssjnamek in forum C Programming
    Replies: 6
    Last Post: 01-26-2006, 07:56 PM
  4. pointers are confusing!
    By ali1 in forum C Programming
    Replies: 10
    Last Post: 09-07-2004, 10:41 PM
  5. functions declaration, pointers, cast, .... CONFUSING
    By Rhodium in forum C Programming
    Replies: 7
    Last Post: 01-09-2003, 05:21 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21