Application of templates in the C standard library: vector template: used to store and manage dynamically growing collections of elements. map template: used to store key-value pairs, the keys can be compared and the values can be of any type. Custom Template Classes: Allows the creation of generic code classes that can be parameterized for different types.
C Templating examples in the standard library
C The standard library makes extensive use of templates to provide reusable, type-safe and Efficient code. Templates are blueprints for creating generic code that can be parameterized for different types.
vector template
vector is a commonly used template container in the C standard library. It is a dynamic array used to store and manage collections of elements.
#include <vector> int main() { // 创建一个空 vector std::vector<int> v; // 添加元素 v.push_back(1); v.push_back(2); v.push_back(3); // 访问元素 for (int i = 0; i < v.size(); i++) { std::cout << v[i] << " "; } // 输出:1 2 3 return 0; }
In this example, the vector template is used to store int type data. We created an empty vector and then added elements using the push_back method. Elements can be accessed via the [] operator.
map template
map is another template container used to store key-value pairs. Keys can be of any comparable type, and values can be of any type.
#include <map> int main() { // 创建一个空 map std::map<std::string, int> m; // 添加键值对 m["Alice"] = 20; m["Bob"] = 30; // 访问值 std::cout << m["Alice"] << std::endl; // 输出:20 return 0; }
In this example, the map template is used to store keys of type string and values of type int. We created an empty map and added key-value pairs using the [] operator. Values can be accessed by key name.
Custom template class
In addition to the templates provided by the standard library, we can also create our own template classes. For example, we can create a template class to find the minimum or maximum value of an element:
template <typename T> T find_max(T a, T b) { return (a > b) ? a : b; } int main() { int max_int = find_max(10, 20); // 返回 20 double max_double = find_max(3.14, 2.71); // 返回 3.14 return 0; }
In this example, the find_max
template function is used to find the minimum or maximum value of two elements maximum value. It can be parameterized against any comparable type, as shown in this example.
The above is the detailed content of Examples of templating in the C++ standard library?. For more information, please follow other related articles on the PHP Chinese website!