Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
修改STL列表中的元素-C++; 我试图用C++中的通用表构造一个二叉搜索树。 class Element { private: list<Element*> _children; char* _name; // and other data members/methods... } 类元素 { 私人: 列出儿童; 字符*\u名称; //和其他数据成员/方法。。。 }_C++_List_Tree_Iterator_Constants - Fatal编程技术网

修改STL列表中的元素-C++; 我试图用C++中的通用表构造一个二叉搜索树。 class Element { private: list<Element*> _children; char* _name; // and other data members/methods... } 类元素 { 私人: 列出儿童; 字符*\u名称; //和其他数据成员/方法。。。 }

修改STL列表中的元素-C++; 我试图用C++中的通用表构造一个二叉搜索树。 class Element { private: list<Element*> _children; char* _name; // and other data members/methods... } 类元素 { 私人: 列出儿童; 字符*\u名称; //和其他数据成员/方法。。。 },c++,list,tree,iterator,constants,C++,List,Tree,Iterator,Constants,如您所见,我有一个类“Element”,它有一个元素指针列表“\u children” 我试图访问这些孩子,以便我可以添加到他们的孩子等等 但是,我无法使用当前使用“const_迭代器”的方法修改这些值,我这样做的原因是_children的“begin()”方法返回一个const_迭代器 有人帮忙吗?谢谢:) 更新:非常感谢大家。。。结果是,我错误地让一个方法返回了_children数据成员的const引用 const list<Element*>& getChildren(

如您所见,我有一个类“Element”,它有一个元素指针列表“\u children”

我试图访问这些孩子,以便我可以添加到他们的孩子等等

但是,我无法使用当前使用“const_迭代器”的方法修改这些值,我这样做的原因是_children的“begin()”方法返回一个const_迭代器

有人帮忙吗?谢谢:)

更新:非常感谢大家。。。结果是,我错误地让一个方法返回了_children数据成员的const引用

const list<Element*>& getChildren();// return [_children]
const list&getChildren();//返回[_儿童]

我刚刚删除了const,现在它工作得很好。谢谢D

如果您想使用子元素作为数组,那么尝试std::vector类而不是std::list如何

这是用法

#include <iostream>
#include <vector>

int main(void) {
    std::vector<int> list;
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    for (int i = 0; i < list.capacity();++i){
        std::cout << list[i] << std::endl;
    }
    return 0;
}
#包括
#包括
内部主(空){
std::向量表;
列表。推回(1);
列表。推回(2);
列表。推回(3);
对于(int i=0;istd::cout如果列表为const,则begin函数将返回一个
const_迭代器
。因此对于
\u子项
列表,您应该能够获得标准迭代器,以便对其执行非const操作:

list<Element*>::iterator it = _children.begin();
list::iterator it=_children.begin();
但是,如果您传递了对列表的常量引用,然后试图从中获取非常量迭代器,则这将不起作用。类似的情况是不允许的:

void doSomething( const list<Element*>& l )
{
    list<Element*>::iterator it = l.begin();
}
void doSomething(const list&l)
{
list::iterator it=l.begin();
}
您需要向列表传递一个非常量引用

另一种不允许的情况是在常量函数中,即

void doSomething() const
{
    list<Element*>::iterator it = _children.begin();
}
void doSomething()常量
{
list::iterator it=_children.begin();
}

但需要查看更多代码才能确认是否正在执行此操作。

查看。
begin()
如果给它一个const对象,则只返回一个
const\u迭代器
。这非常有意义。从这样的正常使用中获取一个可以更改常量值的迭代器将是一个糟糕的设计。我猜您正在调用
\u children.begin()
常量
成员函数中。你确定你需要一个
列表
,而不仅仅是
列表
,甚至是
向量
?是的,OP应该使用
向量
,而不是
列表
,但这并不能回答他提出的问题。