+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 13

Thread: On Learning the STL: Chapter 1 (Vectors) - Part 1

  1. #1
    Join Date
    Jul 2009
    Location
    Santa Clarita, CA
    Posts
    2,111
    Blog Entries
    47
    Rep Power
    31

    On Learning the STL: Chapter 1 (Vectors) - Part 1

    Vectors are a powerful STL container format that closely resembles an array, however is much more useable and intuitive. Vectors allow you to insert, remove, pop, push, change, and resize the array, making it very powerful indeed. It's what C standard arrays would be if they weren't terrible.

    So how do you use a Vector? Easy, just do this:
    Code:
    #include <vector>
    
    int main(){
        std::vector<int> myVector;
        return 0;
    }
    That simple code includes the vector header file, and declares a std::vector for use in your program. The "<int>" part of that vector is because a vector is a class template, which means it can be used to produce an array of any class object you want, from simple int's, pointers, std::strings or even other vectors! Let's start using a vector, and see what we can make!
    Code:
    #include <vector>
    #include <iterator>
    #include <iostream>
    #include <cstdlib>
    
    int main(int argc, char *argv[]) {
        using namespace std;
    
        int aval;
        if (argc == 2) {
            aval = atoi(argv[1]);
        } else {
            cout << "You must input one argument and only one argument!" << endl;
            return 0;
        }
        // Sanity check that input variable...
        if (aval < 1) {
            cout << "Please input a number greater than or equal to 1 to "
                 << "continue." << endl;
            return 0;
        }
    
        // Now let's create and initialize a vector.
        vector<int> myVector;
    
        for (int iii = 0; iii < aval; ++iii)
            myVector.push_back(iii + 1);
    
        // Now let's print out the value of that vector!
        for (int i = 0; (unsigned int)i < myVector.size(); ++i) 
            cout << myVector[i] << " ";
    
        cout << endl;
    
        cout << std::endl;
        return 0;
    }
    (You should be familiar with atoi and accepting command line statements) This code, when run, accepts a command line argument. Go ahead and build it, then, in the command line, enter "{PROGNAME} 25" and it will print out a string of numbers counting from one to 25.

    You may notice that there is no dynamic memory allocation necessary in this program. That is because the vector class template already has that functionality built-in to it, so there's no need to resize it ourselves, we just call "push_back" and vector will do that for us. push_back is a function that adds the value given to it as an argument to the end (or back) of the std::vector. There's a lot more functionality with vectors, so let's try another loop, this time removing each even number from the vector before printing it.
    Code:
    // Now let's create and initialize a vector.
        vector<int> myVector;
    
        for (int iii = 0; iii < aval; ++iii)
            myVector.push_back(iii + 1);
    
        // Remove even numbers, if any.
        for (vector<int>::iterator myIter = myVector.begin();
                                     myIter < myVector.end();
                                                  ++myIter) {
            if (*myIter % 2 == 0)
                myVector.erase(myIter);
        }
    
        // Now let's print out the value of that vector!
        for (int i = 0; (unsigned int)i < myVector.size(); ++i) 
            cout << myVector[i] << " ";
    What we did here was we simply added an additional for loop that initialized a vector iterator, which counted through the vector, and if the value with which the iterator was pointing to, if divided by 2, had a remainder of 0 (IE it was even), then that vector erased the number at the location of myIter.

    That's where the interesting part is, std::vectors also have the ability to erase certain values from within them, then dynamically resize themselves as if the erased value wasn't there at all (this would be very difficult with C arrays). The way this is done is the erase function is provided an iterator that points to the value in the vector array you want to erase, then the function deletes it and moves all of the values ahead of it back one. Go ahead and build that and try it!

    This is just part one on a chapter called "Vectors" for a series On Learning the STL. In the second part we'll take a closer look at iterators and just what they are, as well as how useful they can be, since as you can see, they're going to be used a lot! The attachment contains a copy of the complete code you can build from.

    - Zeke
    Attached Files Attached Files
    Last edited by ZekeDragon; 08-11-2009 at 05:51 PM.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    Join Date
    Jul 2006
    Posts
    16,448
    Blog Entries
    74
    Rep Power
    143

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    Very nice. +rep.
    Programming is a branch of mathematics.
    My CodeCall Blog | My Personal Blog

  4. #3
    mindblaster's Avatar
    mindblaster is offline Newbie
    Join Date
    Jul 2009
    Posts
    17
    Rep Power
    0

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    nice lecture

    Join SuperDiscountShop.com at Facebook.

  5. #4
    Jordan Guest

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    Vectors are powerful, nicely written. +rep

  6. #5
    Join Date
    Oct 2008
    Location
    Istog, Kosova
    Posts
    4,001
    Blog Entries
    1
    Rep Power
    40

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    Awesome! +rep
    Interested in participating in community events?
    Want to harness your programming skill and turn it into absolute prowess?
    Come join our programming events!

  7. #6
    Join Date
    Mar 2008
    Posts
    7,140
    Rep Power
    86

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    Very nice.

    The way this is done is the erase function is provided an iterator that points to the value in the vector array you want to erase, then the function deletes it, moves all of the values ahead of it back one, then resizes the array. Go ahead and build that and try it!
    The thing to note with the erase function is if you do this operation often on big vectors it is going to produce an unwanted overhead on your program and you should use a linked structure. For small vectors this method is good if it is not used a lot.


    Regarding your code to output the vector. You can also use the [] operator to output items. Since the vector is a direct access container this code below would also work.

    Code:
    for (int i=0;i<v.size();i++) {
           cout << v[i] << " ";
    }
    cout << endl;

  8. #7
    Join Date
    Jul 2009
    Location
    Santa Clarita, CA
    Posts
    2,111
    Blog Entries
    47
    Rep Power
    31

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    @chili5:

    True, there is an overhead when using the erase method, however for the size of an array I made it was negligible. The optimal way to do this would probably be to simply iterate through the vector and cout the value if (*myIter % 2) == 0 returns false.

    Quote Originally Posted by chili5 View Post
    Regarding your code to output the vector. You can also use the [] operator to output items. Since the vector is a direct access container this code below would also work.

    Code:
    for (int i=0;i<v.size();i++) {
           cout << v[i] << " ";
    }
    cout << endl;
    Good point, and it probably would have been preferable to use this syntax since we hadn't covered iterators in great detail. I'll go ahead and change it, but change it: "for (int i = 0; (unsigned int)i < v.size(); ++i)" since "i < v.size()" returns a compiler warning and I have allergies to compiler warnings.
    Wow I changed my sig!

  9. #8
    Join Date
    Mar 2008
    Posts
    7,140
    Rep Power
    86

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    Great!

    i < v.size() shouldn't return a compile warning though.

    I think iterators should be a section all on there own. They can be a bit confusing.

  10. #9
    Join Date
    Jul 2009
    Location
    Santa Clarita, CA
    Posts
    2,111
    Blog Entries
    47
    Rep Power
    31

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    Code:
    i < v.size()
    _____________________
    
    >> Warning: Comparison between signed and unsigned integer expressions.
    I deal with it a lot when using for loops. And check the next section, it was supposed to be mostly about iterators, instead I ended up covering constructors, memory management within vectors, and THEN iterators, and I didn't even get all of iterators yet. >_<
    Wow I changed my sig!

  11. #10
    Sallyqq is offline Learning Programmer
    Join Date
    Aug 2009
    Posts
    30
    Rep Power
    0

    Re: On Learning the STL: Chapter 1 (Vectors) - Part 1

    nice tutorial

+ Reply to Thread
Page 1 of 2 12 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. learning python part 4 (a look at functions)
    By saeras in forum Python Tutorials
    Replies: 2
    Last Post: 09-22-2011, 03:13 PM
  2. Learning Python part 0 (prelude)
    By saeras in forum Python Tutorials
    Replies: 8
    Last Post: 07-23-2011, 12:04 PM
  3. Learning Pygame(simple 2d), part 1
    By spyder in forum Python Tutorials
    Replies: 0
    Last Post: 07-24-2010, 02:24 PM
  4. Learning python part 5 (modules)
    By saeras in forum Python Tutorials
    Replies: 1
    Last Post: 02-19-2010, 04:21 AM
  5. On Learning the STL: Chapter 1 (Vectors) - Part 2
    By ZekeDragon in forum C Tutorials
    Replies: 2
    Last Post: 08-11-2009, 12:41 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts