您的位置:首页 > 编程语言 > C语言/C++

C++ back_inserter

2015-11-16 23:05 381 查看
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

// g++ 4.9.2 x86_64
// g++ *.cpp -std=c++11

int main()
{
std::vector<int> vec;
auto it = std::back_inserter(vec); // assigning through it adds elements to vec
*it = 42; // vec now has one element with value 42
for (const auto &e : vec) {
std::cout << e << " ";
}
std::cout << std::endl;

std::vector<int> vec2;
std::fill_n(std::back_inserter(vec2), 10, 0); // appends ten elements to vec2
for (const auto &e : vec2) {
std::cout << e << " ";
}
std::cout << std::endl;

return 0;
}


From C++ Primer (5th) (Section 10.2.2)

back_inserter: Iterator adaptor that takes a reference to a container and

generates an insert iterator that uses push_back to add elements to the

specified container.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: