Question

I want to add contact on some index and i can't figure it out why is this code not working.

I have problem with this line:

a = (*it);

and this one:

tmp.push_back(listOf[a]);

This is the code:

void insert(list<Contact> &listOf, int index, const Contact &info) {

    list<Contact> tmp;
    int a;
    for(list<Contact>::iterator it = listOf.begin(); it != listOf.end(); it++)
    {
        a = (*it);
        if(a == index)
        {
            tmp.push_back(info);
            index -= 2;
            it--;
        }
        else
            tmp.push_back(listOf[a]);
    }
    listOf = tmp;
}

I have structure Contact with name and surname (string).

Maybe is something wrong with just those two lines? Or is it entire code wrong? If it is, i would be glad if someone can get me a solution.

Was it helpful?

Solution

The problem here is that you expect that a list is the same as a vector, and can be used interchangeably.

First of all when you dereference an iterator, it returns the the type of the container, in your case an instance of Contact. Secondly, you can't use array-like indexing on a std::list.

To solve the first problem, you have to keep track of indexes yourself.

To solve the second problem, you already have the iterator and can use that in the push_back call:

tmp.push_back(*it);

OTHER TIPS

It seems that class (or structure) Contact has no conversion function that converts an object of type Contact to an object of type int. So this code is invalid

int a;
//,,,
    a = (*it);

because the type of expression *it is Contact not int.

Also class std::list has no subscript operator. So this statement

tmp.push_back(listOf[a]);

is also invalid and the compiler shall issue an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top