lundi 27 avril 2015

Keeping a pointer to the previous loop value?

I'm trying to iterate over a vector, keeping a copy of the value from the previous iteration. To my surprise, my prev pointer ends up pointing at the current value of loop.

#include <iostream>
#include <vector>

int main() {
    std::vector<std::string> v;
    v.push_back("one");
    v.push_back("two");
    v.push_back("three");

    std::string *prev = nullptr;
    for (std::string s : v) {
        std::cout << "s: " << s << std::endl;
        if (prev == nullptr) {
            std::cout << "prev: (null)" << std::endl << std::endl;
        } else {
            std::cout << "prev: " << *prev << std::endl << std::endl;
        }
        prev = &s;
    }

    std::cout << "final prev: " << *prev << std::endl;
}

Here's the output:

s: one
prev: (null)

s: two
prev: two

s: three
prev: three

final prev: three

Why is this? What's the right way to fix it?

Aucun commentaire:

Enregistrer un commentaire