存储指向映射中对象的指针
Store pointers to an object in map
我有一个指向vector<object>
的矢量指针,所以const std::vector<object> vecPtr* = &vec;
现在我想以这种方式填充std::multimap<std::string, object*> dataMap;
,其中key
是object.name
,value
是pointer to an object
。
我试过
for(std::vector<object>::const_iterator it = data->cbegin(); it != data->cend(); ++it){
dataMap.insert(std::pair<std::string, object*>(it->name, &it));
}
但是我犯了一个错误。
error: no matching function for call to 'std::pair<std::basic_string<char>, object*>::pair(const string&, std::vector<object>::const_iterator*)'
dataMap.insert(std::pair<std::string, object*>(it->name, &it));
^
我做错了什么?
我知道指针使我的生活复杂化,但我想避免复制对象
为了避免复制对象,请考虑使用对象的引用。此外,考虑使用共享指针,例如std::shared_ptr(对于C++11)或boost::shared-ptr。一个好的风格是避免手动分配内存。让我们用STL提供的一种自动方式来完成它。
class Object{};
typedef boost::shared_ptr < Object > ObjectPtr;
然后
std::multimap < std::string, ObjectPtr > map;
创建只使用对象的实例:
ObjectPtr obj = boost::make_shared < Object > ();
&it
是指向迭代器的指针,而不是指向对象的指针。如果要获得指向对象的指针,请编写&*it
。
之后,您会看到一个错误,说您无法从const object*
转换为object*
——这是因为您使用的是const_iterator
。所以,根据你的需要,你可以做两件事。
如果您不打算更改其中的对象,请将dataMap
声明为std::multimap<std::string, const object*> dataMap;
。
或者使用iterator
:
for (std::vector<object>::iterator it = data->begin(); it != data->end(); ++it) {
dataMap.insert(std::pair<std::string, object*>(it->name, &*it));
}
顺便说一下,这个循环可以重写为:
for (auto& a : *data) {
dataMap.insert({a.name, &a});
}
相关文章:
- 对象指针在c++中是如何工作的
- C++ 对象指针数组的复制构造函数
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 正确初始化和销毁对象指针的C++数组?
- 如何深度复制链表对象指针
- 对象指针 c++ 的全局向量错误
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 静态对象指针
- 正在将对象指针数组初始化为NULL
- 如何使用条件表达式返回对象指针?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 使用C对象指针构建PyObject*
- 如何在使用对象指针时访问成员函数
- 静态强制转换允许转换对象指针,但不允许转换整数
- C++ abort() 在函数内的抽象类对象指针调用上
- 指向函数的对象指针
- 访问指向对象指针向量的指针的第一个元素?
- 如何将对象/指针正确存储到 Qlist 中
- 对象指针打印结果以相反的顺序进行