Thread: pass a vector as argument

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    17

    pass a vector as argument

    Hi

    How do you pass a vector array as an argument to a function? What's the syntax?

    Thank you

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >How do you pass a vector array as an argument to a function?
    A vector, or an array of vectors? I find your choice of words ambiguous. Here's both:
    Code:
    void a ( vector<int>& v );
    void b ( vector<int> av[] );
    
    ...
    
    int main()
    {
      vector<int> v;
      vector<int> av[10];
    
      a ( v );
      b ( av );
    }
    But if it's the latter, you really should be using a vector of vectors instead of an array of vectors.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    17
    Hi

    Sorry, I'm new to this, I mean't just a vector. I'm using a vector instead of an array because I need to get the size, and I don't know how to get the size of an array.

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >and I don't know how to get the size of an array
    Save it as a variable and pass it into your function:
    Code:
    void f ( int array[], int size );
    
    int main()
    {
      const int size = 10;
      int array[size];
    
      f ( array, size );
    }
    But using vectors is better anyway, so you stumbled on the superior solution for a different reason. Anyway, in my previous post, look at how I declared and called a(), that should show you how to pass a vector to a function. If you want the vector to be read-only, you can make it const:
    Code:
    void a ( const vector<int>& v );
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to List Iterator As Function Argument
    By bengreenwood in forum C++ Programming
    Replies: 8
    Last Post: 06-17-2009, 05:30 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Variable Argument functions
    By dnysveen in forum C++ Programming
    Replies: 13
    Last Post: 06-01-2006, 06:03 PM
  4. Nested loop frustration
    By caroundw5h in forum C Programming
    Replies: 14
    Last Post: 03-15-2004, 09:45 PM
  5. Parameter pass
    By Gades in forum C Programming
    Replies: 28
    Last Post: 11-20-2001, 02:08 PM