Reputation: 2576
I have a function which return value
if a key
exist in map
like:
map<int,string> mymap;
//Assume there are some key value pair in above map
string & ReturnKey(int &a)
{
string ret;
map<int,string>::iterator iter = mymap.find(a);
if(iter not_eq mymap.end())
{
ret = iter->second;//I think this will make copy
}
else
return ret;
}
How can I avoid copy of string which is returning from above function?
Upvotes: 0
Views: 100
Reputation: 227390
You can return a reference to an existing string or raise an exception if it doesn't exist. This is easily done with the std::map::at
method:
string& ReturnKey(int a)
{
return mymap.at(a);
}
If you are stuck with a pre-C++11 compiler, you have to do it by hand:
string& ReturnKey(int a)
{
map<int,string>::iterator iter = mymap.find(a);
if(iter == mymap.end())
throw std::out_of_range("Invalid key");
return iter->second;
}
Upvotes: 1
Reputation: 73061
If you're okay with the returned reference being const, you can do something like this:
const string & ReturnKey(int a)
{
static const string defaultValue; // to be returned if object isn't found
map<int,string>::iterator iter = mymap.find(a);
if(iter != mymap.end())
{
return iter->second;
}
else return defaultValue;
}
It's safe to return a reference to (defaultValue) in the not-found case because defaultValue is declared static and therefore will still exist after the function returns. In the value-found case, the caller will need to be careful not to hold the reference and try to use it after mymap has been cleared or modified, but that's usually not an issue in practice.
Upvotes: 1
Reputation: 1521
As in your program you can not return the reference of the variable declared inside the function because as the function complete the execution all the variable declared inside that function will get released and deleted.
So in that case you will get null
or garbage value
every time the function will called.
For this In my opinion you can pass your string argument as a reference
in the function.
so, by using this you can get your desired value in your variable.
Or
You can also change the return type of the function to std::string
.
I think You have to use this function as:
map<int,string> mymap;
//Assume there are some key value pair in above map
void ReturnKey(int &a, string& str)
{
map<int,string>::iterator iter = mymap.find(a);
if(iter not_eq mymap.end())
{
str = itr->second;
}
}
Or you can return std::string
values for status of your operation.
As follows:
map<int,string> mymap;
//Assume there are some key value pair in above map
std::string ReturnKey(int &a)
{
std::string ret;
map<int,string>::iterator iter = mymap.find(a);
if(iter not_eq mymap.end())
{
ret = iter->second;//I think this will make copy
}
else{
delete ret;
return null;
}
return ret;
}
and #include <string>
should be used.
Hope this will help you.
Upvotes: 0