我对更改或替换列表中的元素有疑问。我有一个类:
class Node{
public:
elType type; // enum
string name;
Node(elType type, string name);
~Node();
void printNodeInfo();
}
和一个列表:
std::list <Node * > someList;
现在我如何替换此类元素中的值(对于简单的更改类型)。 我试过这个:
std::list<Node * >::iterator it = someList.end();
it--;
while(openName.compare((*it)->name) != 0)
it--;
(*it)->type = otherType;
但是好像不行,类型还是一样。如果有任何帮助,我将不胜感激。
编辑: 我更新了列表,所以现在我有:
std::list <Node> someList;
并将替换更改为:
it->type = otherType;
我也试过:
std::list<Node >::iterator it2 = someList.erase(it);
Node temp(otherType, openName);
someList.insert(it2, temp);
在这两种情况下,一个简单的打印方法:
it2->printNodeInfo();
什么都不输出。
最佳答案
我不知道你的问题到底是什么,但这是你的解决方案:
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Node{
public:
int type; // enum
string name;
Node(int type, string name) : type(type), name(name) {}
~Node(){}
void printNodeInfo() const {cout << type << ", " << name << endl;}
};
void replace(list<Node> &l, const string &nameSearch, int typeReplace) {
for (auto it = l.rbegin(); it != l.rend(); it++) {
if (it->name == nameSearch) {
it->type = typeReplace;
/* To stop searching */
return;
}
}
/* Nothing replaced, error message? */
}
int main() {
list<Node> l;
l.push_back(Node(0, "World"));
l.push_back(Node(1,"Hello"));
l.push_back(Node(2,"World"));
replace(l, "World", 42);
for (const auto &el: l) {
el.printNodeInfo();
}
return 0;
}
关于c++ - 如何更改STL列表中项目的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37437773/