如何访问std::list指定索引元素并修改其值?
问题解决:修改std::list指定索引的元素值
你的代码问题出在迭代器的赋值方式:你直接把info赋值给了迭代器变量it,这是修改迭代器本身,而非它指向的Student元素。正确的做法是对迭代器进行解引用后再赋值。
修正后的完整Insert函数代码
#include <list> #include <string> struct Student { std::string Name; std::string ID; }; void Insert(std::list<Student>& List, int index, Student info) { if (index < 0 || index >= List.size() || List.empty()) { return; } else { std::list<Student>::iterator it = List.begin(); std::advance(it, index); // 解引用迭代器,修改指向的目标元素 *it = info; } }
关键说明
std::advance(it, index):由于std::list的迭代器是双向迭代器,不支持随机访问,因此需要用advance将迭代器移动到指定索引位置,该操作的时间复杂度为O(n)。*it = info:通过解引用迭代器it,获取它指向的Student对象,再将info的值赋值给这个对象,完成元素修改。
另外,原代码中的List.empty() == true可简化为List.empty(),逻辑完全一致。
内容的提问来源于stack exchange,提问作者Potomoto
相关产品推荐
相关产品推荐

