除了,allocator空间分配器之外,<memory>中还有初始化容器标准库函数.
分别为:
template<typename _InputIterator, typename _ForwardIterator>
inline _ForwardIterator uninitialized_copy(_InputIterator __first, _InputIterator __last,_ForwardIterator __result)
template<typename _ForwardIterator, typename _Tp>
inline void uninitialized_fill(_ForwardIterator __first, _ForwardIterator __last,const _Tp& __x)
template<typename _ForwardIterator, typename _Size, typename _Tp>
inline void uninitialized_fill_n(_ForwardIterator __first, _Size __n, const _Tp& __x)
/* * File: main.cpp * Author: Vicky.H * Email: [email protected] */ #include <iostream> #include <memory> #include <cstring> struct st_A { char name[21]; short age; }; namespace cn_vicky_uninitialized { /** * stl的源码分析 * @param first * @param n * @param val */ template <class For, class Size, class T> inline void uninitialized_fill_n_stl(For first, Size n, const T& val) { // typedef typename std::iterator_traits<For>::value_type VT; // while (n--) std::_Construct(std::__addressof(*first++), static_cast<VT>(val)); while (n--) std::_Construct(std::__addressof(*first++), val); } /** * 自定义简洁版 * @param first * @param n * @param val */ template <class For, class Size, class T> inline void uninitialized_fill_n(For first, Size n, const T& val) { typedef typename std::iterator_traits<For>::value_type VT; while (n--) new (static_cast<void*> (&*first++)) VT(val); /**区别于stl版本使用construct函数,我们使用new 来分配空间*/ } } /* * */ int main(void) { st_A st_A_arr[10]; std::cout << st_A_arr[0].name << std::endl; std::cout << st_A_arr[0].age << std::endl; std::cout << st_A_arr[9].name << std::endl; std::cout << st_A_arr[9].age << std::endl; std::cout << "---------------------------" << std::endl; // 使用stl库函数填充 st_A a; strcpy(a.name, "Vicky"); a.age = 25; std::uninitialized_fill_n(st_A_arr, 10, a); std::cout << st_A_arr[0].name << std::endl; std::cout << st_A_arr[0].age << std::endl; std::cout << st_A_arr[9].name << std::endl; std::cout << st_A_arr[9].age << std::endl; std::cout << "---------------------------" << std::endl; strcpy(a.name, "Lily"); a.age = 24; cn_vicky_uninitialized::uninitialized_fill_n_stl(st_A_arr, 10, a); std::cout << st_A_arr[0].name << std::endl; std::cout << st_A_arr[0].age << std::endl; std::cout << st_A_arr[9].name << std::endl; std::cout << st_A_arr[9].age << std::endl; std::cout << "---------------------------" << std::endl; // 使用自定义 strcpy(a.name,"Jack"); a.age = 18; cn_vicky_uninitialized::uninitialized_fill_n(st_A_arr, 10, a); std::cout << st_A_arr[0].name << std::endl; std::cout << st_A_arr[0].age << std::endl; std::cout << st_A_arr[9].name << std::endl; std::cout << st_A_arr[9].age << std::endl; return 0; }