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; Ok hello, I went to my references and then the compiler and tried some stuff out. I came up with ...

  1. #16
    dreamerv3
    Guest

    Lightbulb New question in the same thread, didn't want to start a new thread.

    Ok hello, I went to my references and then the compiler and tried some stuff out.

    I came up with some interesting conclusions, but something in my new from scratch code doesn't work right.

    I guess my original question has been answered, but now after trying various things with the compiler, I have a quandary, and this one seems simple yet it doesn't work.

    skipper, you said the following in a recent reply.

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

    Skipper:
    Absolutely arbitrary. Doesn't even need to be a single char variable. Give it a name like 'forCntr' if that's your preference.

    I tried variables like: short container = 0;

    And then tried to do: Weight[container];

    I got a segmentation fault when executing that build.

    Well I tried all sorts of single character alpha variables and they all would let me populate the vector as shown below:

    Code:
    vector <short> Weight(10);
    
    short i = 0;
    short x = 0;
    short c = 0;
    
    for ( i = 0, i < 10, i++)
    {
    Weight[x] = i;
    c = Weight[x];
    cout << "The current number is: " << c << endl;
    }
    This would output, the quote plus the numbers 0-9. Thats great, but then I tried to access an individual element of the vector and cout that value and it would only give me a zero.

    This is what I tried:
    Code:
    for ( i = 0, i < 10, i++)
    {
    Weight[x] = i;
    c = Weight[x];
    cout << "The current number is: " << c << endl;
    }
    
    cout << "Here is the number 4: " << Weight[5] << endl;
    What I got on execution was:

    Here is the number 4: 0

    I tried storing the Weight[5] in other variables like g,y,q, but they all return 0. I am initialiazing everything upon declaration to 0 to avoid garbage. But the assignments come afterwards. So that can't be doing it.

    I like vectors, because they are dynamic, I'm going to try single dimensional arrays next but this should work shouldn't it?

    I mean am I missing something here?

    Can't I just assign like this:

    c = Weight[5];

    Aren't accessing elements the whole point of the "[]"

    I didn't want to start up a new thread since this was already here and is vaguely related to the subject line.

    Thanks, and sorry if this sounds like I'm not treading water, you're answers really haelped with the previous questions.

    And about learning the STL, won't that happen as I progress through my c++ books? Is there a separate STL book or internet resource aside from the c++ references.

    The way it was worded made it seem like STL is a separate thing to learn.

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

    Ouch!

    Let's backtrack.

    The variable in the FOR loop is arbitrary. Could be i, x, y, z, forCntr.
    Code:
    short i = 0;
    for (forCntr = 0; forCntr < 5; forCntr++)
    {
       Weight[forCntr] = i++;
    }
    This code places 0, 1, 2, 3, 4 into the array, Weight[].

    When you access Weight[2], you will retrieve the value '2'. (Note that the subscript '2' is the third element of the array. Subscripts start at '0'.)
    Can't I just assign like this:

    c = Weight[5];
    The right side of the assignment operator (=) is evaluated first. Therefore, your code would assign the value contained in Weight[5] to 'c'. If Weight[5] contains no value, then 'c' is assigned a bunch of NULL characters.

    About the STL, do some research. There are many excellent sources. One favorite of mine is Object-Oriented Programming in C++ by Robert LaFore(ISBN 1-57169-160-X). It's a textbook, but does, from my perspective, a very good job of explaining/developing work with the Standard Template Library.

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

  3. #18
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Okee, let's take this from the TOP DOWN! Not from the middle to the top to the bottom to the mid-top to the mid-low and back to the middle.

    This is what a for loop does:
    Code:
    for(int i = 0; i < 5; ++i)
    {
         //stuff
    }
    Let's take this apart.

    the "int i = 0;", as you might guess, declares and initializes a variable called "i" to 0. It happens at the very beginning of the loop.

    Next, is "i < 5". The loop will keep repeating until this is not true.

    Last, is "++i" or "i++". At the end of each time the loop repeats (as in, after "stuff"), this will be executed.

    But you could also do this:
    Code:
    int i;
    
    for(i = 0; i < 5; ++i)
    {
         //stuff
    }
    It will do the same thing. But the 1st example will declare and define "i" at the beginning of the for loop, while the second will declare "i" before and then assign it the value 0 at the start of the loop.

    Next, put in weight.
    Code:
    std::vector<int> weight(5);
    
    for(int i = 0; i < 5; ++i)
    {
         weight[i] = i;
    }
    Vectors work sort of like arrays, but can do more... for these purposes, "std::vector<int> weight(5);" does the same thing as "int weight[5];"

    "weight[i]" will give you the i'th value in the vector called "weight". So "weight[i] = i" will assign the value of "i" to "weight[i]".

    The first time the loop executes, i is given the value 0. "i < 5" is true, so the loop executes. It does "weight[i] = i;". So that is the same as saying "weight[0] = 0" since i is 0. So that is the end of the loop, so it does "++i", which makes i 1 higher. So i is 1 now. i is still less than 5, so the loop executes. Now, "weight[i] = i;" means "weight[1] = 1;", because i is 1. And so on, until i gets to 4. Then it goes through the loop, and ++i is executed again. Now i is 5, and "i < 5" is false. So the loop quits, and this is what weight looks like:

    weight[0] = 0
    weight[1] = 1
    weight[2] = 2
    weight[3] = 3
    weight[4] = 4

    There is no weight[5], because weight only has 5 values, and the index starts at 0.

    So THAT is the end of it, the complete simple no-garbage version that I hope will make everything clear. Good luck!

    P.S. I think what got dreamer confused earlier was people not carefully reading/understanding dreamer's posts and saying "absolutely!" to things that shouldn't have been mentioned in the first place. Let's all try to read posts a little more carefully from now on!

    P.P.S. 'for these purposes, "std::vector<int> weight(5);" does the same thing as "int weight[5];"'
    This is only to make things easier to understand! Do NOT take this literally; it works like that in the example, but that is not by any means how vectors work! It was only meant to help understand what the [i] does (it does the same thing as in an array, but vectors are NOT arrays!).
    Last edited by Hunter2; 08-12-2002 at 07:50 PM.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  4. #19
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    Hunter2,

    It will do the same thing. But the 1st example will declare and define "i" in the for loop, while the second will declare "i" before and then assign it the value 0 at the start of the loop.
    True, but don't forget that "int i;" is, in fact, a declaration and definition.

    Sticky little bit of information, and one that I would have argued over myself. A variable declaration sets aside a location in memory for the value of the variable. That makes it a "definition" as well. The "assignment", of course, is another issue.

    P.S. I think what got dreamer confused earlier was people not carefully reading/understanding dreamer's posts and saying "absolutely!" to things that shouldn't have been mentioned in the first place. Let's all try to read posts a little more carefully from now on!
    With all due respect, I, and jdinger, answered the questions that were posed. Your information is welcome, but you might try reading the individual posts...carefully...before you criticize the answers that were offered.

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

  5. #20
    Hunter2
    Guest
    oh... right. I suppose you're right about the declaration/definition, but I thought there was supposed to be a difference?... I never did study that in detail.

    And pardon me about the thing about not reading posts carefully... I suppose you and jdinger did read them carefully, and the responses were accurate and true, but they were just a mite confusing to the beginner (those posts might not have been yours, though). Nobody seemed to explicitly discourage the idea (or encourage other ideas) that weights was a sort of template doojigger and weights[i] meant "a weights called i", and weights[asdf] would be "a weights called asdf".

  6. #21
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    Hunter2,
    I suppose you're right about the declaration/definition, but I thought there was supposed to be a difference?
    Internally, of course, there is. The tendency is to think that, without the assignment operator and a value, there is no 'definition'. Not true.
    And pardon me about the thing about not reading posts carefully...
    I'm a little surprised at your indignation here. I was certainly more respectful of you than you were of jdinger and me.

    We frequently tread a fine line between talking over someone's head and insulting his/her intelligence out here. Personally, I'm on a roll because I've been accused of both recently. As you've seen firsthand, what looked rather straightforward at the outset, took some unexpected turns. Okay. We deal with it. Hopefully, we're successful in the process.

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

  7. #22
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    I'm a little surprised at your indignation here
    Actually, I thought "pardon me" was supposed to be polite?... Oh well, no matter I actually meant it to be more like "sorry, I guess that was a little misworded about (...)." But it was too long to type out, and I guess I was a bit lazy
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  8. #23
    Much older and wiser Fountain's Avatar
    Join Date
    Dec 2001
    Location
    Engeeeerland
    Posts
    1,158
    hehe now now...

    overview is that hunter must be a teacher or something....

    I was impressed by your explanation hunter! Straight out of a lecturers mouth...with no jargon...keep up the good answers!

    No offence intended to the two of you answering them before, but it was a bit long winded dont you think?
    Such is life.

  9. #24
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    Fountain,

    No offense taken. It was long-winded...though we've yet to hear from dreamerv3 and whether, or not, he/she understands what's going on.

    Hunter2,

    I apologize for the misinterpretation. In retrospect, it does come off as being polite. Fresh start?

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

  10. #25
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Fountain,

    No teacher, just a grade 10 student! (!) Thanks anyways I think I got the explanation skills from teaching math to a dunce during class when I was in grade 6...


    Skipper,

    Shure, why not?
    We should all kiss and make up.

    -some unknown philosopher
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

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

    Sorry, no kissing. There are laws...

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

  12. #27
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Haha!
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  13. #28
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    Fountain, my answers were far from long winded. As it was I was fighting conciousness that day and struggling to keep from falling head first into my keyboard!

  14. #29
    Registered User
    Join Date
    Apr 2002
    Posts
    362
    Oh, that's nice, jdinger, ol' buddy! The would make me the one with the fat mouth! (Of course, I did suggest that you presented the Reader's Digest version that day - a compliment, by the way - but I did stick up for you later and I'm going to leave you on the hook with me.)

    Now, quit weasling, apologize to the whole board and get back to work.

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

  15. #30
    Used Registerer jdinger's Avatar
    Join Date
    Feb 2002
    Posts
    1,065
    I didn't think of it as leaving you hanging, Skip. You said yourself that my answer was a bit compact.

    Originally posted by skipper
    Now, quit weasling, apologize to the whole board and get back to work.
    Funny you should say that. I just realized it's lunch time and I haven't touched my code for almost 30 minutes! Well, guess I'll have to finish it up after lunch. It's a good thing I don't get paid by the hour, or else I might feel bad!

Page 2 of 3 FirstFirst 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, 05:22 PM
  2. Most confusing language
    By Suchy in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 04-22-2007, 10:08 PM
  3. confusing error messages?
    By ssjnamek in forum C Programming
    Replies: 6
    Last Post: 01-26-2006, 08:56 PM
  4. pointers are confusing!
    By ali1 in forum C Programming
    Replies: 10
    Last Post: 09-07-2004, 11:41 PM
  5. functions declaration, pointers, cast, .... CONFUSING
    By Rhodium in forum C Programming
    Replies: 7
    Last Post: 01-09-2003, 06:21 AM

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