|
|
Home » Community » Newbie corner » Pick Semantics: Passing a Vector to a method
Pick Semantics: Passing a Vector to a method [message #40143] |
Thu, 20 June 2013 21:42  |
NeilMonday
Messages: 15 Registered: May 2013
|
Promising Member |
|
|
I am learning about pick semantics now. Lets assume I wanted to print a Vector of Strings two times. Am I right in assuming that this will not work:
void PrintNames(Vector<String> names)
{
for(int i=0; i<names.GetCount(); i++)
{
//print the name
}
}
int main()
{
Vector<String> myNames;
//add a few Strings to myNames here...
PrintNames(myNames);
//myNames is not valid anymore?
PrintNames(myNames);
}
Instead I will need to do this:
void PrintNames(Vector<String> names)
{
for(int i=0; i<names.GetCount(); i++)
{
//print the name
}
}
int main()
{
Vector<String> myNames;
//add a few Strings to myNames here...
Vector<String> tempNames;
tempNames <<= myNames;
PrintNames(tempNames);
tempNames <<= myNames;
PrintNames(tempNames);
}
|
|
|
Re: Pick Semantics: Passing a Vector to a method [message #40146 is a reply to message #40143] |
Fri, 21 June 2013 06:24  |
|
Hi Neil,
Welcome to the forum
NeilMonday wrote on Thu, 20 June 2013 21:42 | I am learning about pick semantics now. Lets assume I wanted to print a Vector of Strings two times. Am I right in assuming that this will not work:
void PrintNames(Vector<String> names)
{
for(int i=0; i<names.GetCount(); i++)
{
//print the name
}
}
int main()
{
Vector<String> myNames;
//add a few Strings to myNames here...
PrintNames(myNames);
//myNames is not valid anymore?
PrintNames(myNames);
}
|
Yes, you understand that correctly. The first call would "pick" the contents of the original vector and the second call would show nothing or even thrown error.
NeilMonday wrote on Thu, 20 June 2013 21:42 | Instead I will need to do this:
void PrintNames(Vector<String> names)
{
for(int i=0; i<names.GetCount(); i++)
{
//print the name
}
}
int main()
{
Vector<String> myNames;
//add a few Strings to myNames here...
Vector<String> tempNames;
tempNames <<= myNames;
PrintNames(tempNames);
tempNames <<= myNames;
PrintNames(tempNames);
}
|
This would work, but it has terrible overhead. It is not necessary to copy the vector at all, you can just to pass it to the PrintNames as a reference (in this case you can even use const reference):
// all you need to do is to add one little '&' ;-) the const is optional
void PrintNames(const Vector<String>& names)
{
for(int i=0; i<names.GetCount(); i++)
{
//print the name
}
}
int main()
{
Vector<String> myNames;
//add a few Strings to myNames here...
PrintNames(myNames);
PrintNames(myNames);
}
Since there is now no copying, there is no pick to worry about In general, you should use references as often as possible, it is a great boost to performance, especially for large containers.
Best regards,
Honza
|
|
|
Goto Forum:
Current Time: Wed Apr 30 17:38:30 CEST 2025
Total time taken to generate the page: 0.00864 seconds
|
|
|