By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,193 Members | 843 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,193 IT Pros & Developers. It's quick & easy.

Returning reference to vector from function

P: 4
Hello:

What is the syntax for returning a reference to a vector from a function? I have a private vector and I want to return it using a public get function (like in the code below), but I believe that what I have will make a copy of the vector, and my real vector is several hundred bytes. Do I have to cast it as a constant? What is the syntax for that (or where does one look)?

Sorry if these are basic questions - alas, I've been scouring the internet for several days now!!!

Many thanks for any assistance you can offer!

Michele
Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. #include <vector>
  3. #include "VectorThing.h"
  4. using namespace std;
  5.  
  6. VectorThing::VectorThing()
  7. {
  8.         vect.push_back("macaroni");
  9.         vect.push_back("cheese");
  10.  
  11. }
  12.  
  13. vector <string> VectorThing::getVector()
  14. {
  15.         return vect;
  16. }
  17.  
  18. And this is my header file:
  19.  
  20. #include <string>
  21. #include <vector>
  22. using namespace std;
  23.  
  24. class VectorThing
  25. {
  26.         public:
  27.                 VectorThing();
  28.                 vector <string> getVector();
  29.  
  30.         private:
  31.                 vector <string> vect;
  32.  
  33. };
Mar 22 '07 #1
Share this Question
Share on Google+
3 Replies


sicarie
Expert Mod 2.5K+
P: 4,677
Please use code tags around your code - it helps greatly with readability.

Why not just declare the vector locally?
Mar 22 '07 #2

Expert 100+
P: 1,510
try using &, e.g.
Expand|Select|Wrap|Line Numbers
  1. vector <string>  & VectorThing::getVector()
  2. {
  3.         return vect;
  4. }
  5.  
but this will give read/write access to the vector from outside the class, e.g.
Expand|Select|Wrap|Line Numbers
  1.     vector<string> &v1=v.getVector();
  2.     cout << v1[0] << endl;
  3.     v1[1]="salad";
  4.  
You could return a constant reference
Expand|Select|Wrap|Line Numbers
  1. const vector <string>  & VectorThing::getVector()
  2. {
  3.         return vect;
  4. }
  5.  
which would give read access but not write
Mar 22 '07 #3

P: 4
Thanks!!! That is exactly what I was looking for. I was trying some version of that but I thought I had to cast the vector to return it as a constant. But as it compiles I see now that I don't!

Thanks!
Michele
Mar 23 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.