【问题标题】:Store pointers to an object in map在地图中存储指向对象的指针
【发布时间】:2014-12-19 04:30:20
【问题描述】:

我有一个指向vector<object> 的向量指针,所以 const std::vector<object> vecPtr* = &vec;

现在我想以这种方式填写std::multimap<std::string, object*> dataMap;,其中keyobject.namevaluepointer 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));
                                                                          ^

我做错了什么?

我知道指针会让我的生活变得复杂,但我想避免复制对象

【问题讨论】:

  • 你应该确切地提到你得到的错误是什么。
  • 这看起来很可疑。您将指针传递给迭代器。 'dataMap.insert(std::pair<:string object>(it->name, &it))*
  • 你实际上是把迭代器的地址加到映射中,而不是指向对象的指针。
  • @Oncaphillis 所以我应该在末尾添加一个 * 吗?
  • vecPtr 没有声明为指针,无论如何它似乎与问题的其余部分没有任何关系。

标签: c++ pointers object map


【解决方案1】:

为了避免复制对象考虑使用对象的引用。此外,考虑使用共享指针,例如 std::shared_ptr(用于 C++11)或 boost::shared_ptr。一种好的方式是避免手动分配内存。让我们以 STL 提供的自动方式进行。

class Object{};
typedef boost::shared_ptr < Object > ObjectPtr;

然后

std::multimap < std::string, ObjectPtr > map; 

创建 Object 的实例只需使用:

ObjectPtr obj = boost::make_shared < Object > ();

【讨论】:

  • 智能指针听起来很有用,但我还没有了解它们:/
【解决方案2】:

&amp;it 是指向迭代器的指针,而不是指向对象的指针。如果你想得到一个指向对象的指针,写&amp;*it

之后,您会看到一条错误消息,指出您无法从 const object* 转换为 object* - 这是因为您使用的是 const_iterator。因此,根据您的需要,您可以做两件事。

如果您不打算更改其中的对象,请将dataMap 声明为std::multimap&lt;std::string, const object*&gt; 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});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多