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

C++语法基础--泛型算法(generic algorithm)--插入迭代器back_inserter(),front_insertor(),inserter()以及next()函数简介

2013-07-12 15:33 281 查看
今天研究迭代器时发现原来for循环可以这样写:



int my_array[5] = {1, 2, 3, 4, 5};

for (int &x : my_array)

{

cout<<x;

}

百度了一下才知道:C++11支持以范围为基础的 for 循环。看来又要多花点时间去掌握C++11的新特性了。

1.标准库所定义的迭代器不依赖于特定的容器,事实上C++还提供了另外三种迭代器:

*插入迭代器

*iostream迭代器

*反向迭代器

2.C++提供三种插入器

*back_inserter:使用push_back实现插入的迭代器

Constructs a back-insert iterator that inserts new elements at the end of x.



原型:

template <class Container>

back_insert_iterator<Container> back_inserter (Container& x);



解析:

x :

Container on which the iterator will insert new elements.

Container should be a container class with member push_back defined.

return:

A back_insert_iterator that inserts elements at the end of container x.

Example:

int main()

{

int arr[]={1,2,3};

vector<int> vec(arr,arr+3);

fill_n(back_inserter(vec), 3, -1);

for (int n : vec)


{

cout << n << ' ';

}

}

//output://1 2 3 -1 -1 -1

*front_inserter:使用push_front实现插入

类似于back_inserter,这里就不举例了

*inserter: 使用insert实现插入

Constructs an insert iterator that inserts new elements int x at the position pointed by it.



原型:

template< class Container >

std::insert_iterator<Container> inserter( Container& c, typename Container::iterator i );

Example:



int main()

{

int arr[]={1,2,3,4,5};

list<int> lst(arr,arr+5);

fill_n(inserter(lst, next(lst.begin(),2)), 3, -1);



for (int n : lst)

{

cout << n << ' ';

}



}

Output:1 2 -1 -1 -1 3 4 5





3.next()

Returns an iterator pointing to the element that it would be pointing to if advanced n positions.

原型:

template <class ForwardIterator>

ForwardIterator next (ForwardIterator it,

typename iterator_traits<ForwardIterator>::difference_type n = 1);

解析:

it : an iterator

n : number of elements to advance

Return :The nth successor of iterator it.

Example:

int main()

{

int arr[]={1,2,3,4};

vector<int> v(arr,arr+4);

vector<int>::iterator it = v.begin();

vector<int>::iterator nx = std::next(it, 2);

cout << *it << ' ' << *nx << '\n';//1 3

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