DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: pass vector to function

  1. #1
    Join Date
    Feb 2009
    Posts
    2

    pass vector to function

    Hi All,

    I am trying to pass a pointer or reference of a vector into a function but I am getting confused.

    Basically I have several non global vectors that i need to add to using push_back() from within a function.

    Here's some example code using only 1 vector but it doesn't compile, can anybody give me a clue?

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    void function(vector<int> *);
    
    int main(int argc, char *argv[]) {
    
    	vector<int> alpha;
    
    	alpha.push_back(1);
    
    	cout << alpha.size() << endl;
    
    	function(&alpha);
    
    	cout << alpha.size() << endl;
    }
    
    void function(vector<int> * alpha){
    	*alpha.push_back(1);
    }
    Thanks in advance!

  2. #2
    Join Date
    Feb 2009
    Posts
    2
    i solved it!

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    //void function(vector<int> *);
    void function(vector<int> &alpha);
    
    int main(int argc, char *argv[]) {
    
    	vector<int> alpha;
    
    	alpha.push_back(1);
    
    	cout << alpha.size() << endl;
    
    	function(alpha);
    	function(alpha);
    
    	cout << alpha.size() << endl;
    }
    
    void function(vector<int> &alpha){
    	alpha.push_back(1);
    }

  3. #3
    Join Date
    Nov 2003
    Posts
    4,118
    Good. Anyway, when passing a pointer to a vector, you need to use -> to access the vector's members:

    void function(vector<int> * alpha){
    alpha->push_back(1);
    }
    Danny Kalev

Similar Threads

  1. call function for button
    By angela_quests in forum VB Classic
    Replies: 2
    Last Post: 04-13-2007, 04:57 AM
  2. comparing function pointers [was: typedef problem]
    By swapnil_paranja in forum C++
    Replies: 20
    Last Post: 08-25-2005, 03:54 PM
  3. Getting a list of files into an array
    By Scott in forum VB Classic
    Replies: 12
    Last Post: 12-21-2001, 05:21 PM
  4. Getting a GUI to function
    By Eric in forum Java
    Replies: 1
    Last Post: 11-27-2001, 07:53 AM
  5. AnimateWindow API
    By Tim Manos in forum VB Classic
    Replies: 4
    Last Post: 10-19-2001, 06:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center