Using STL function objects can improve reusability, including the following steps: Define the function object interface (create a class and inherit from std::unary_function or std::binary_function) Overload operator() to define the function behavior in the overloaded Implement the required functions in operator() and use function objects through STL algorithms (such as std::transform)
Use STL function objects to improve code reusability
STL function object is a callable class that allows combining functional programming with object-oriented programming. By encapsulating code logic in function objects, you can improve reusability and encapsulation.
Steps:
std::unary_function
Or std::binary_function
. Overload operator()
to define function behavior. operator()
, implement the required functions. std::transform
or std::for_each
. Example:
Suppose we want to create a function object to calculate the length of a string:
class StringLength { public: int operator()(const std::string& str) { return str.length(); } }; int main() { std::vector<std::string> names = { "John", "Mary", "Bob" }; std::vector<int> lengths; std::transform(names.begin(), names.end(), std::back_inserter(lengths), StringLength()); for (int length : lengths) { std::cout << length << " "; // 输出:4 4 3 } std::cout << "\n"; return 0; }
In this example, StringLength
The class is a function object that implements the logic of calculating the length of a string. We apply it to the string vector names
via std::transform
, storing the calculated length into the lengths
vector.
By using custom function objects, we can achieve code reuse and easily apply the logic of calculating string length to different string collections.
The above is the detailed content of How to design custom STL function objects to improve code reusability?. For more information, please follow other related articles on the PHP Chinese website!