简体   繁体   中英

Dereferencing iterator to pointers correctly

I have a vector of pointers to objects. Each object stores a value and has a toString() function that returns that value as a string. I have an iterator to go through the vector and I need to extract the value of each object by calling toString(). The problem is, I can't figure out how to get the value.

This function is ultimately supposed to write the number to a file, but I'm using the cout for testing.

    void writeNumbers(vector<Integer*>& input)
    {
        ofstream write;
        write.open("Integers.txt");
        vector<Integer*>::iterator iter = input.begin();
        for (iter; iter < input.end(); iter++)
        {
            **std::cout << (*iter)->toString() << std::endl;**
        }
        write.close();

I get an Access Violation error which points me to the toString() function:

    std::string Integer::toString()
    {
        std::stringstream ss;
        ss << *(this)->value;
        return ss.str();
    }

toString() works fine whenever I don't try to access it through the iterator.

Edit: Value in toString is actually a pointer to a number.

Edit2: New writeNumbers:

void writeNumbers(vector<Integer*>& input)
{
    ofstream write;
    write.open("Integers.txt");
    vector<Integer*>::iterator iter = input.begin();
    for (iter; iter != input.end(); iter++)
    {
        std::cout << (*iter)->toString() << std::endl;
    }
    write.close();
}

Final Edit : Alright, the problem turned out to be a borked constructor that was failing to initialize a pointer properly, so I was WAY off base on where the problem actually was. :)

Integer::Integer(string input)
{
if(isNaN(input))
value = new int(atoi(input.c_str()));
}

So it should have been !isNaN, plus I fixed the problem of initializing it on bad input:

//New constructor, works 100%
Integer::Integer(string input)
{
if(!isNaN(input))
    value = new int(atoi(input.c_str()));
else
    value = new int(0);
}

Your toSting() has the issue. Change

ss <<*(this)->value;

to

ss << value;

EDIT: This is not an error, but a general advice when using iterators. Dont use < to check for end, use != .

iter < input.end()

It should be like this:

iter != input.end()

This is because for certain containers, the < operator will not do what you expect. As a result, at some point you could be dereferencing input.end() itself, which points at nothing.

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