用BOOST_FOREACH修改std::vector中的指针
Modifying pointers in std::vector with BOOST_FOREACH
我有一个类node
并声明为std::vector<node*>
。我想使用BOOST_FOREACH来迭代向量,但是我有一个小问题。
data_flow_graph* dfg;
node* other_node;
[...]
BOOST_FOREACH(node* n, vector_of_nodes){
if (n->get_id() < 100)){
n = new node(last_id++);
n->add_related_node(other_node);
dfg->add_node(n);
}
}
这是,我试图修改指针的地址,同时迭代它。问题是,虽然创建了新节点,但vector_of_nodes
中的指针保持不变。我猜这是Boost如何管理对指针的访问的问题,因为如果我使用常规迭代器进行等效处理:
std::vector<node*>::iterator it;
std::vector<node*>::iterator et = vector_of_nodes.end();
for (it = vector_of_nodes.begin(); it != et; ++it){
if ((*it)->get_id() < 100)){
(*it) = new node(last_id++);
(*it)->add_related_node(other_node);
dfg->add_node(*it);
}
}
代码运行良好,并按预期执行。
我可以用那个版本,但我很好奇…为什么第一个版本不行?
将代码改为
BOOST_FOREACH(node*& n, vector_of_nodes){
if (n->get_id() < 100)){
n = new node(last_id++);
n->add_related_node(other_node);
dfg->add_node(n);
}
}
因为在你的版本中你改变了本地指针的地址。在使用n = new node
之前,为什么不删除old呢?既然手动管理资源有问题,为什么不使用smart pointers
呢?
相关文章:
- std::vector::迭代器是否可以合法地作为指针
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- 我无法使用C++指针指向类方法返回的 std::vector
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 指向基类的指针的 std::vector 的深层副本
- 从 std::vector 迭代器中执行函数指针
- 将 std::vector::d ata 传递给函数期望类型**(双指针)
- 根据指针条件初始化std::vector
- 释放 std::vector 中指针内存的最有效方法是什么?
- 在实现 std::vector 时,我必须拥有 end() 的"end"指针吗?
- 将双指针作为参数传递给需要引用 std::vector <double>的函数
- 如何将 std::string 赋回作为 <char>void* 指针传递的 std::vector.data()?
- 将此类的智能指针追加到成员 std::vector
- 为什么 std::vector<>::const_reference 可以转换为非常量指针?
- SWIG:传递一个 std::vector< std::vector <double> >指向 python 的指针
- 带有 std::vector 的指针算术
- 从vector<指针*>vector<指针*比;在c++中
- 如何获取指向原始数据的std::vector指针
- c++的vector指针,vector的声明和指针的删除