Thread: STL Vector problem with code

  1. #16
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Lets write something closer to real C++ code. I've put the comments inside the code for convenience.
    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main() {
        // In C++ we don't declare all variables up front at the start of our function.
        // instead the normal thing to do is to declare them near their point of first use.
        // That way, if we were to say exit this function say when the user entered a negative
        // number then the program wouldn't have wasted time initialising the vector. Not too
        // important here obviously, but it can become very important in a larger program.
        int numberOfElements = 0;
    
        // A while loop was not appropriate here. That's because you intended the loop to
        // always be run at least once. The way to do that is not to assign a value to make
        // the condition true beforehand, but to make it a "do .. while" instead. That's what
        // they're for! In this instance a for (;;) loop with a break statement would work at
        // least as well too though, and save testing for the same condition twice.
        do {
              cout << "How many numbers will you be entering?" << endl; 
              cin >> numberOfElements;
              cin.ignore();
              
              if (numberOfElements <= 0) {
                  // You had two semi-colons on this line before.
                  cout << endl << "Error... Please enter a positive integer" << endl;
              }
        } while (numberOfElements <= 0);
        
        cout << " Enter the numbers:\n\t\t\t";
        // Why use \n all of a sudden instead of endl? endl doesn't have to go at the end
        
        // The vector only gets initialised once we reach this line.
        vector<int> array;
        // vectors already keep track of how many items they contain. You're not supposed to
        // also track it separately in a variable of your own. Simply use the .size() method to find
        // out how many items it holds. arrayNumber and the finished flag were not needed.
        while (array.size() < numberOfElements) {
             int temp; // Nothing outside this loop needs to even know temp existed, so here is a good place for it.
             cin >> temp;
             array.push_back(temp);
             cin.ignore();
        }
    
        // sum and loopNumber can be declared here. as loopNumber is just a for-loop
        // counter the normal thing to do is to declare it inside the for loop. Personally
        // I would use a shorter name.
        float sum = 0;
        // It's safer to use array.size() here in case the code changes later.
        for (size_t loopNumber = 0; loopNumber < array.size(); loopNumber++) {
            sum += array[loopNumber];
        }
        // Serious C++ programmers would replace the loop above with one call to std::accumulate
        
        // Also pay attention to the clean use of whitespace in this code vs what was posted earlier
        cout << "Average equals: " << sum / numberOfElements;
        cin.get();
    }
    P.S. The grammatical error in Elysia's sig always bothers me. ("every thing" should be "everything")
    You don't have to feed Elysia's ego anyway
    Last edited by iMalc; 02-16-2010 at 01:59 AM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  2. #17
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Real programmers would write std::vector<int>::size_t or shorter, std::size_t instead of int
    int will give you signed/unsigned mismatch on VC++!
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #18
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    // Why use \n all of a sudden instead of endl? endl doesn't have to go at the endl
    endl == '\n' + flush
    What's the point of flushing in the middle of output?
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #19
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by Elysia View Post
    Real programmers would write std::vector<int>::size_t or shorter, std::size_t instead of int
    int will give you signed/unsigned mismatch on VC++!
    Close. One would probably use a typedef for std::vector<int> and use something like IntVector::size_type.
    <escuse> I daren't have compiled the code though, it's up to the person learning from it to find my bugs </escuse>

    endl == '\n' + flush
    What's the point of flushing in the middle of output?
    A valid point. I wouldn't have put tabs after it myself, hence the endl would be on the end. I just didn't go so far as to say that the tabs should go.

    Cleaning up other's code is like being a vacuum cleaner salesman. No matter how many people have vacuumed the same rug, you can always demonstrate how much more dirt your vacuum cleaner can lift out that other vacuum cleaners "missed".
    Last edited by iMalc; 02-16-2010 at 12:17 PM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #20
    Registered User
    Join Date
    May 2009
    Posts
    106
    wow... this recieved alot of attention lol... I know that you should declare variable near to where there first use is going to be but since the program was so small I just declared hem in the begging.... oh yeah and not trying to like be mean... but in c++ theres a thing called a
    Code:
    /*
    BLOCK COMMENT......
    ....
    ....
    .....
    .......
    */

  6. #21
    Registered User NeonBlack's Avatar
    Join Date
    Nov 2007
    Posts
    431
    jamort, a lot of people don't like block comments because they can't be nested.
    And most IDEs have automatic line commenting/uncommenting for blocks of code.
    I copied it from the last program in which I passed a parameter, which would have been pre-1989 I guess. - esbo

  7. #22
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Actually I am a fan of block comments. It's just that since the viewer for this forums doesn't colour the comments differently, I thought this might be easier to read.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proposal: Code colouring
    By Perspective in forum A Brief History of Cprogramming.com
    Replies: 28
    Last Post: 05-14-2007, 07:23 AM
  2. Values changing without reason?
    By subtled in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 10:20 AM
  3. Array of Vectors amd other STL questions
    By kolistivra in forum C++ Programming
    Replies: 16
    Last Post: 04-12-2007, 09:11 AM
  4. Updated sound engine code
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 11-18-2004, 12:38 PM
  5. Replies: 4
    Last Post: 01-16-2002, 12:04 AM