Designing Callbacks in C++
Callback is a function that we pass to another APIs as argument while calling them.
function pointer callback as an argument is as follows,
| 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 | 
std::string buildCompleteMessage(std::string rawData, std::string (* encrypterFunPtr)(std::string) ) 
std::string buildCompleteMessage(std::string rawData, std::string (* encrypterFunPtr)(std::string) )  
{ 
    // Add some header and footer to data to make it complete message 
    rawData = "[HEADER]" + rawData + "[FooTER]"; 
    // Call the callBack provided i.e. function pointer to encrypt the 
    rawData = encrypterFunPtr(rawData); 
    return rawData; 
} | 
Find & Replace all sub strings – using STL
#include <iostream>
#include <string>
void findAndReplaceAll(std::string & data, std::string toSearch, std::string replaceStr)
{
 // Get the first occurrence
 size_t pos = data.find(toSearch);
 // Repeat till end is reached
 while( pos != std::string::npos)
 {
  // Replace this occurrence of Sub String
  data.replace(pos, toSearch.size(), replaceStr);
  // Get the next occurrence from the current position
  pos =data.find(toSearch, pos + toSearch.size());
 }
}
int main()
{
 std::string data = "Boost Library is simple C++ Library";
 std::cout<<data<<std::endl;
 findAndReplaceAll(data, "Lib", "XXX");
 std::cout<<data<<std::endl;
 return 0;
}
 
No comments:
Post a Comment