Potomoto
Potomoto

Reputation: 11

How to acces element in std::list and change its value?

struct Student 
{
    string Name;
    string ID;
};

So I have a structure in which I have the given strings.

void Insert(list<Student>& List, int index, Student info)
{
    if (index< 0 || index>= List.size() || List.empty() == true)
    {
        return;
    }
    else
    {

    }
}

In the "else" area, I want to access the element with the given index and change the value in it to info.

I have tried with the following lines, and it didn't work?

std::list<Student>::iterator it = List.begin();
std::advance(it, index);
it = info;

Upvotes: -1

Views: 98

Answers (1)

JeJo
JeJo

Reputation: 33092

in the "else" area I want to access the element with the given index and change the value in it to info [...]

You were almost there. You have to dereference the iterator to access the underlying element. That means, you have to

*it = info;
^^ --> dereferencing

or better move the info into it, if the info is not further used inside the function scope.

*it = std::move(info);
^^ --> dereferencing

That being said, if you want to access the iterator by index, there are better alternatives, such as std::array(if the array size is fixed and known by compile time, std::vector (if the array size is dynamic), etc.)

Upvotes: 3

Related Questions