直接上代码吧:
template<class T, size_t nSize>
void printArray(T(&Array)[nSize]) {T* pt = Array;for (size_t n = 0; n < nSize; ++n) {cout << *(pt + n) << "\t";}cout << "\n";
} int main() {int ia[] = {27,210,12,47,109,83};char ca[] = "C++";printArray(ia);printArray(ca);
}
输出:
参考源码:std::begin() std::end()
#include<xutility>
_EXPORT_STD template <class _Ty, size_t _Size>
_NODISCARD constexpr _Ty* begin(_Ty (&_Array)[_Size]) noexcept {return _Array;
}_EXPORT_STD template <class _Ty, size_t _Size>
_NODISCARD constexpr _Ty* end(_Ty (&_Array)[_Size]) noexcept {return _Array + _Size;
}
int main() {int ia[] = { 27,210,12,47,109,83 };int val = 83;int* result = find(begin(ia), end(ia), val);}
可以使你设计的容器能用数组初始化,添加一个构造函数,例如:
/// <summary>/// 用数组初始化列表/// </summary>/// <typeparam name="nSize"></typeparam>/// <param name="_Array"></param>/// 创建时间: 2024-10-06 最后一修改时间:2024-10-06template<size_t nSize>inline _DList(T(&_Array)[nSize]) {InitData();for (const T& t : _Array) { Add(t); }}
用法例子:
int main() {int ia[] = { 27,210,12,47,109,83 };_pn(ia);_DList<int> dl = ia; _pn(dl); }
输出: