unique_ptr用法 - 类的地图 [英] unique_ptr usage - map of class
问题描述
任何人都可以帮助我下面的代码显示类对象的内容?
Can anyone help me with the code below to display the contents of the class object?
Q1 - 任何人都可以确认 - 如果这是在地图中存储指向表类对象的指针的正确方法?
Q1 - can anyone confirm - if this is the correct way to store the pointer to table class object in the map?
Q 2 - 如何输出地图中整个记录的内容?
Q 2 - How to output the contents on the entire record in the map?
感谢
#include <iostream>
#include <map>
#include <memory>
#include <string>
class Table
{
public:
int c1, c2, c3;
Table() {}
Table(int _c1,int _c2,int _c3)
{
c1=_c1;
c2=_c2;
c3=_c3;
}
};
int main()
{
std::map<int, std::unique_ptr<Table>> mapTable;
std::unique_ptr<Table> up(new Table(1,2,3));
// Is this correct way to store the pointer?
mapTable.insert(std::make_pair(0,std::move(up)));
// How can I display c1,c2,c3 values here with this iterator?
for (const auto &i : mapTable)
std::cout << i.first << " " << std::endl;
return 0;
}
// How to get the output in the form - 0,1,2,3 ( 0 map key, 1,2,3 are c1,c2,c3 )
// std::cout << i.first << " " << i.second.get() << std::endl; --> incorrect output
推荐答案
可以任何人确认 - 如果这是正确的方式来存储指向表类对象在地图中?
Q1 - can anyone confirm - if this is the correct way to store the pointer to table class object in the map?
是的,在容器中存储 unique_ptr
的正确方法。唯一指针是不可复制的,所以你需要 std :: move()
时,它传递给一个函数 - 你这样做。
Yes, that is the correct way of storing a unique_ptr
in a container. Unique pointers are non-copyable, so you need to std::move()
it when passing it to a function - and you are doing that.
Q 2 - 如何输出地图中整个记录的内容?
Q 2 - How to output the contents on the entire record in the map?
除非我缺少一些显而易见的东西,否则你实际上做的最困难的部分。只要执行:
Unless I am missing something obvious, you actually did the hardest part of the job. Just do:
for (const auto &i : mapTable)
{
std::cout << i.first << " " << std::endl;
std::cout << i.second->c1 << std::endl;
std::cout << i.second->c2 << std::endl;
std::cout << i.second->c3 << std::endl;
}
迭代器是 std :: pair< const int,std :: unique_ptr< Table>>
(这是映射的值类型),因此 i.first
访问密钥, i.second
提供对映射值(在您的情况下是唯一指针)的访问。
The iterator is an iterator to a std::pair<const int, std::unique_ptr<Table>>
(which is the value type of the map), so i.first
provides access to the key, and i.second
provides access to the mapped value (the unique pointer, in your case).
这篇关于unique_ptr用法 - 类的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!