Thread: return vector<string> function

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    45

    return vector<string> function

    How do i call that function so that i can use the vector in main?

    thanks!

    Code:
    vector<string> function();
    
    int main()
    {
        //what goes here?
    }
    
    vector<string> function()
    {
        vector<string> s(3);
        s[0] = "one";
        s[1] = "two";
        s[2] = "three";
    
        return s;
    }

  2. #2
    C/C++Newbie Antigloss's Avatar
    Join Date
    May 2005
    Posts
    216
    Code:
    int main()
    {
        //what goes here?
        vector< string > vec( function() );
    }

  3. #3
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    The return Type of the function is a vector<string> so it has to return a vector of strings... all you do is create another vector<string> in main and asign it the function.

    Just as Antigloss showed you

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    You have a variety of options depending on your knowledge base and needs. Antigloss' version uses the copy constructor of vectors to transfer information from
    from function() to main(). However, you could use the assignment operator:

    Code:
    vector<string> function();
     
    int main()
    {
    	vector<string> vec;
    	vec = function();
    }
     
    vector<string> function()
    {
    	vector<string> s(3);
    	s[0] = "one";
    	s[1] = "two";
    	s[2] = "three";
     
    	return s;
    }
    or you could use a single vector passed back and forth by reference:
    Code:
    void function(vector<string> &);
     
    int main()
    {
    	vector<string> s(3);
    	function(s);
    }
     
    void function(vector<string> & rS)
    {
    	rS[0] = "one";
    	rS[1] = "two";
    	rS[2] = "three";
    }
    Last edited by elad; 07-18-2005 at 09:24 AM.
    You're only born perfect.

  5. #5
    Registered User
    Join Date
    Aug 2004
    Posts
    45
    thanks, i could not figure out how to assign that vector in the main.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM