Thread: cannot add on vectors statically

  1. #1

    Question cannot add on vectors statically

    I am using vectors for array purposes in my program. I declared my vector as a global variable.
    I'm initializing it with some values at first in main. Let's say with 3 members. And then i pass the vector to a function as a parameter and try to add to more elements inside the function. But after i return back form the function the two elements are not appended. I thought that vector should be having "pass by reference" mechanism just as arrays but i'm not sure if this is my problem. Or what could the problem be?Is there something special with vector usage?
    Thanks in advance...

  2. #2
    Registered User
    Join Date
    Aug 2002
    Hermosa Beach, CA
    If it is really a global variable you shouldnt need to pass it into the function at all. If you want to pass it by reference anyway, you need to explicitly do it, ie:

    void myfunction(vector<MyType>& vec)
    // do something with vector
    The crows maintain that a single crow could destroy the heavens. Doubtless this is so. But it proves nothing against the heavens, for the heavens signify simply: the impossibility of crows.

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Visalia, CA, USA
    Your assumption isn't stupid. However keep in mind that a vector doesn't work the same as an array. It works by allocating memory stacks to hold data. Therefore, when you don't pass a vector by reference the function will make a copy of the vector and your code will make changes to the copied (and temporary) object not the one passed into it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to input a data file to parallel vectors
    By Wink- in forum C++ Programming
    Replies: 13
    Last Post: 10-30-2007, 05:24 PM
  2. Adding vectors ??
    By Hussain Hani in forum C++ Programming
    Replies: 1
    Last Post: 11-18-2006, 03:03 AM
  3. Help needed Please
    By jereland in forum C Programming
    Replies: 9
    Last Post: 03-18-2004, 05:30 AM
  4. Can somebody test this code please
    By andy bee in forum C Programming
    Replies: 6
    Last Post: 10-09-2001, 03:08 PM