- The Modern C++ Challenge
- Marius Bancila
- 125字
- 2021-06-25 22:01:27
19. Adding a range of values to a container
Writing functions with any number of arguments is possible using variadic function templates. The function should have the container as the first parameter, followed by a variable number of arguments representing the values to be added at the back of the container. However, writing such a function template can be significantly simplified using fold expressions. Such an implementation is shown here:
template<typename C, typename... Args>
void push_back(C& c, Args&&... args)
{
(c.push_back(args), ...);
}
Examples of using this function template, with various container types, can be seen in the following listing:
int main()
{
std::vector<int> v;
push_back(v, 1, 2, 3, 4);
std::copy(std::begin(v), std::end(v),
std::ostream_iterator<int>(std::cout, " "));
std::list<int> l;
push_back(l, 1, 2, 3, 4);
std::copy(std::begin(l), std::end(l),
std::ostream_iterator<int>(std::cout, " "));
}
推薦閱讀
- Unity 2020 By Example
- Vue 3移動Web開發與性能調優實戰
- Learning Neo4j
- JavaScript從入門到精通(微視頻精編版)
- Mastering Adobe Captivate 2017(Fourth Edition)
- ASP.NET Core 5.0開發入門與實戰
- Magento 2 Theme Design(Second Edition)
- Practical Data Science Cookbook(Second Edition)
- Spring實戰(第5版)
- 運用后端技術處理業務邏輯(藍橋杯軟件大賽培訓教材-Java方向)
- 匯編語言編程基礎:基于LoongArch
- C++編程兵書
- 區塊鏈國產化實踐指南:基于Fabric 2.0
- R Data Science Essentials
- Data Manipulation with R(Second Edition)