vector of pointers vs vector of values

This is a discussion on vector of pointers vs vector of values within the C++ Programming forums, part of the General Programming Boards category; there are two ways that i know of to create vectors vector<type> or vector<type*> with the former you must call ...

  1. #1
    Shadow12345
    Guest

    vector of pointers vs vector of values

    there are two ways that i know of to create vectors
    vector<type> or vector<type*>
    with the former you must call
    vector.resize(number_instances_of_type);
    the latter
    vector.push_back(new type);

    I was thinking about the way memory is allocated. when you get right down to it they both must allocate memory in much the same way, the only obvious difference being vector.push_back(new type) calls the constructor. anything you guys can add to or correct in these statements?

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    With the former you can call vector.push_back(type());
    With the latter, you can call vector.resize(number_of_pointers_to_type);

    If you are constructing objects (non-primitives), their constructor is always called. IE, vector.push_back(type()) constructs a default instance of type, then calls it's copy constructor.

    Code:
    #include <vector>
    #include <iostream>
    
    class test {
    public:
    	test() {
    		std::cout << "test::test()" << std::endl;
    	}
    	test(const test& o) {
    		std::cout << "test::test(const test&)" << std::endl;
    	}
    };
    
    int main() {
    	std::vector<test> vecOfValues;
    	vecOfValues.push_back(test());
    	
    	std::vector<test*> vecOfPointers;
    	vecOfPointers.resize(3); // 3 null pointers
    	for (int i = 0; i < 3; ++i) {
    		std::cout << vecOfPointers[i] << '\n';
    	}
    	return 0;
    }
    Use a vector of values unless you need polymorphism.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  2. Replies: 1
    Last Post: 02-03-2005, 03:33 AM
  3. Pointers equal non--&-ed values
    By C++Child in forum C++ Programming
    Replies: 6
    Last Post: 07-31-2004, 08:06 PM
  4. Displaying pointer's actual values in inheritance
    By Poof in forum C++ Programming
    Replies: 14
    Last Post: 07-29-2004, 08:34 AM

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