Re: STL Vector - pass by reference?
- From: "Scott McPhillips [MVP]" <org-dot-mvps-at-scottmcp>
- Date: Thu, 09 Aug 2007 16:52:46 -0400
Gerry Hickman wrote:
Hi,
In an earlier thread entitled "STL vector - which style of for() loop?" I had a function that could populate a vector (with a variable number of strings) and pass it back to the caller, but people pointed out this would create a "copy" of the vector and it may be better to pass by reference. Doug Harrison offered this example:
----- example start -----
I would use pass-by-reference to avoid this needless cost, e.g.
vector<string>::size_type
void GetDeviceClasses(vector<string>& guids)
{
guids.clear();
// If you can estimate n, reserve can eliminate reallocations.
// guids.reserve(n);
...
returns guids.size();
}
----- example end -----
but when I came to actually code this, I ran into some problems. I managed to code something that appears to achieve the objective, but my code is almost "back-to-front" (in terms of * and &) of what Doug posted. Can someone clarify?
----- my attempt -----
using namespace std; // just for this demo
vector<string> guids;
PopulateStrings(&guids);
cout << "Count of guids is now " << guids.size(); // prints 2
void PopulateStrings(vector<string> * guids)
{
guids->clear();
guids->push_back("test1");
guids->push_back("test2");
}
----- end my attempt -----
There are two ways to "pass by reference." They are to pass a reference, or to pass a pointer. Doug showed using a reference, your version is using a pointer. Performance would be equal either way.
--
Scott McPhillips [MVP VC++]
.
- References:
- STL Vector - pass by reference?
- From: Gerry Hickman
- STL Vector - pass by reference?
- Prev by Date: Re: Converting LBYTE to int
- Next by Date: Re: STL Vector - pass by reference?
- Previous by thread: STL Vector - pass by reference?
- Next by thread: Re: STL Vector - pass by reference?
- Index(es):
Relevant Pages
|