How do I change the code using a lambda expression?
I am learning C ++ using a lambda expression. I just tried changing the code that was already coded using or at the time, then I have a question about lambda.
I am just changing the code using lambda or for_each (C ++ 11). How to change?
Here's the code to change.
std::string PointToString(void* p_pData)
{
char* p = (char*)p_pData;
int iLength = 0;
std::memcpy(&iLength, p, sizeof(int));
p += sizeof(int);
std::string sRet;
std::array<char, 3> szB;
sRet.append("0x");
for ( int i = 0; i < iLength; i++ )
{
sprintf(szB.data(), "%02X", (unsigned char)*(p++));
sRet.append(szB.data());
}
return sRet;
}
This code will simply convert the memory value to hexadecimal code. This function is called like this.
char szB[15] = {0x0b, 0x00, 0x00, 0x00, 0xc7, 0xd1, 0xb1, 0xdb, 0xc0, 0xd4, 0xb4, 0xcf, 0xb4, 0xd9, 0x2e};
void* p = nullptr;
p = (void*)szB;
sRet = PointToString(p);
The result could be 0x0B000000C7D1 .....
I want to try lambda in PointToString function. How can I change this function?
source to share
Well, you could write:
std::for_each(p, p + iLength, [&](unsigned char ch)
{
sprintf(szB.data(), "%02X", ch);
sRet.append(szB.data());
});
&
means that you will work from szB
and sRet
from the link, instead of working with their copies.
IMHO this is not a significant improvement over your original code.
source to share