c++ - 如何更改STL列表中项目的值?

标签 c++ stl

我对更改或替换列表中的元素有疑问。我有一个类:

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/

相关文章:

c++ - 对于最大吞吐量,UDP 数据包的最佳大小是多少?

c++ - 打开CV : unresolved external symbol

c++ - 在忽略符号的同时分配变量? (c++)

c++ - 使用基于动态/状态的分配器的 STL 实现?

设置范围构造函数的 C++ 行为?

c++ - 不能在 vector 的 vector 上 emplace_back() 花括号初始化器

c++ - DirectX:在设备之前获取InfoQueue

c++ - back_insert_iterator<> 按值传递安全吗?

c++ - vector 迭代器不递增

c++ - 顺序或解析器 a || b