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

C++语法基础--泛型算法(generic algorithm)--写入容器元素的算法fill(),fill_n,replace()

2013-07-12 04:33 573 查看
*fill

Assigns val to all the elements in the range [first,last)

原型:

template <class ForwardIterator, class T>

void fill (ForwardIterator first, ForwardIterator last, const T& val);

该算法等效于:

template <class ForwardIterator, class T>

void fill (ForwardIterator first, ForwardIterator last, const T& val)

{

while (first != last) {

*first = val;

++first;

}

}

Example:

int main ()

{

vector<int> myvector (8); // myvector: 0 0 0 0 0 0 0 0

fill (myvector.begin(),myvector.begin()+4,1);
// myvector: 1 1 1 1 0 0 0 0

fill (myvector.begin()+3,myvector.end()-2,2); // myvector: 1 1 1 2 2 2 0 0




//myvector contains:

for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)

{

cout << ' ' << *it;// 1 1 1 2 2 2 0 0

}



return 0;

}

*fill_n


Assigns val to the first n elements of the sequence pointed by first.

原型:

template <class OutputIterator, class Size, class T>

void fill_n (OutputIterator first, Size n, const T& val);

该算法等效于:

template <class OutputIterator, class Size, class T>

OutputIterator fill_n (OutputIterator first, Size n, const T& val)

{

while (n>0) {

*first = val;

++first; --n;

}

return first; // since C++11

}

Example:

int main ()

{

vector<int> myvector (8,1); // myvector: 1 1 1 1 1 1 1 1

std::fill_n (myvector.begin(),4,2); // myvector: 2 2 2 2 1 1 1 1



//myvector contains:

for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)

{

cout << ' ' << *it;//2 2 2 2 1 1 1 1

}

return 0;

}



Tips:

fill_n假定对指定数量的元素做写操作时是安全的,所以要确保容器有足够的空间。

*replace

Assigns new_value to all the elements in the range [first,last) that compare equal to old_value.

原型:

template <class ForwardIterator, class T>

void replace (ForwardIterator first, ForwardIterator last,

const T& old_value, const T& new_value);

该算法等效于:

template <class ForwardIterator, class T>

void replace (ForwardIterator first, ForwardIterator last,

const T& old_value, const T& new_value)

{

while (first!=last) {

if (*first == old_value) *first=new_value;

++first;

}

}

Example:

int main ()

{

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

vector<int> myvector (myints, myints+8); // 1,1,1,3,2,2,1,3



replace (myvector.begin(), myvector.end(), 3, 2);// 1,1,1,2,2,2,1,2



//myvector contains:

for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)

{

cout << ' ' << *it;// 1,1,1,2,2,2,1,2

}



return 0;

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