C++:使用fill_n函数操作容器

问题及注意

编写程序,使用fill_n()将一个序列中的int值都设置为0.

++++++++++++++++++PS注意:++++++++++++++++++++

!!!!!!注意:

不能在一个空容器上调用fill_n(或类似的写元素的算法).

—————–>

vector vec;//空向量.
//灾难:修改vec中的10个(不存在)元素.
fill_n(vec.begin(),10,0);

<---------------end. 这个调用是一场灾难。我们指定了要写入10个元素,但vec中并没有元素————它是空的。这条语句的结果是未定义的。 +++++++++++++++++++++++++++++++++++++++++++++++++++++

C++.
image-2089

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*************************************************************************
    > File Name: test.10.6.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2014年06月07日
 ************************************************************************/

#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;

/*****************************
 
    编写程序,使用fill_n()将一个序列中的int值都设置为0.
   
    ++++++++++++++++++PS注意:++++++++++++++++++++

    !!!!!!注意:

        不能在一个空容器上调用fill_n(或类似的写元素的算法).

        ----------------->

        vector<int> vec;//空向量.
        //灾难:修改vec中的10个(不存在)元素.
        fill_n(vec.begin(),10,0);

        <---------------end.

        这个调用是一场灾难。我们指定了要写入10个元素,但vec中并没有元素————它是空的。这条语句的结果是未定义的。

    +++++++++++++++++++++++++++++++++++++++++++++++++++++

 *************************************/


void outv(vector<int> v)
{
    for(vector<int>::const_iterator it=v.begin();it!=v.end();++it)
    {
        cout << *it << endl;
    }
}

int main()
{
    vector<int> vec;
    vec.push_back(0);
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    cout << "未改变之前:" << endl;
    outv(vec);
    fill_n(vec.begin(),vec.size(),0);
    cout << "改变之后:" << endl;
    outv(vec);
    return 0;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据