简体   繁体   中英

After using a transform to fill up a vector, the new c++11 for loop doesn't work

I am currently learning STL, and am on a topic of mapping, filtering etc. I recently learned lots of new stuff such as the new c++11 for loop(with auto) I (kinda) don't understand the way things work, but i wanted to use the "transform" function to fill up another vector(mapping topic). But after i build the program and run it, it gives me an error which goes as: "cannot seek value-initialized vector iterator"

I am not sure what that means or what error there is, could you guys help me understand the for loop concept and what im doing wrong here?

ps the operator of the "transform" in the end was done with a lambda thingy(which i still have to learn and have no idea about) in the tutorial, i tried to make a function and guessed that it would work.

int mult(int a) {
    return a * 10;
}
int main() {
    vector<int> v{ 1,2,3,4,5 };
    vector<int> v1;
    for (auto& i : v) {
        cout << i << endl;
    }
    if (v1.empty()) cout << "v1 is empty" << endl;
    cout << "v1" << endl;
    transform(v.begin(), v.end(), v1.begin(), mult);
    for (auto &i : v1) {
        cout << i << endl;
    }
}

transform doesn't extend a range, it only writes to on an existing one that's assumed non-empty. v1 is empty, so it cannot be made to store the result of the transformation. Your options are to either make sure v1 holds enough elements for the algorithm to overwrite:

vector<int> v1(v.size());

or to use std::back_inserter to create an iterator which increases the size of v1 :

transform(v.begin(), v.end(), back_inserter(v1), mult);

This is UB (undefined behaviour), it does not fill anything:

transform(v.begin(), v.end(), v1.begin(), mult);

you want:

std::transform(v.begin(), v.end(), std::back_inserter(v1), mult);

As a general rule, operations on begin/end iterators do not change the size of the container.

Your code just spewed data into an empty buffer, corrupting memory or worse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM