开发者

why should i use back_inserter in function generate_n?

开发者 https://www.devze.com 2023-04-09 17:05 出处:网络
hi guys i will show three codes 1 and 2 makes s开发者_运维技巧ame work but the third one doesnt work. I want to understand why doesnt work or why do work the other two ? (strrand function produces ran

hi guys i will show three codes 1 and 2 makes s开发者_运维技巧ame work but the third one doesnt work. I want to understand why doesnt work or why do work the other two ? (strrand function produces random string)

1.

int main(){
    vector<string> svec(50);
    randomize();

    generate_n(svec.begin(), 20, strrand);
    display(svec.begin(), svec.end());

    return 0;
}

2.

int main() {
    vector<string> svec;
    randomize();

    generate_n(back_inserter(svec), 20, strrand);
    display(svec.begin(), svec.end());

    return 0;
}

3.

int main(){
    vector<string> svec;
    randomize();

    generate_n(svec.begin(), 20, strrand);
    display(svec.begin(), svec.end());

    return 0;
}


The third has undefined behavior. In the first, you specify the vector size where you define the vector. That means it starts as a vector of 50 default-initialized (empty) strings. You then overwrite those strings with your random strings.

In the second, you use a back_insert_iterator to add the strings to the vector individually.

In the third, you start with an empty vector, and you attempt to use the (invalid) iterator to its (nonexistent) beginning. You then write 20 strings starting at whatever spot in memory its (random) initial value happens to refer to. You have not, however, at any time actually inserted a string into the vector. A vector normally keeps a count of how many items it current contains; in your third case, that will start out 0, and remain 0 throughout. When you attempt to show the "contents", you should get nothing (though, since you've already had undefined behavior at that point, anything is possible -- especially if some of the data you wrote happened to overwrite part of the vector's internal data.

What you have is a marginally more subtle (but equally problematic) version of well known beginner mistakes like:

char *s;

strcpy(s, "This will give UB");
0

精彩评论

暂无评论...
验证码 换一张
取 消