gpt4 book ai didi

c++ - unique_ptr 用法 - 类图

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:55 26 4
gpt4 key购买 nike

谁能帮我用下面的代码来显示类对象的内容?

Q1 - 任何人都可以确认 - 这是否是在 map 中存储指向表类对象的指针的正确方法?

Q 2 - 如何输出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()将它传递给函数时使用它 - 而您正在这样做。

Q 2 - How to output the contents on the entire record in the map?

除非我遗漏了一些明显的东西,否则您实际上完成了工作中最困难的部分。只是做:

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>> 的迭代器(这是 map 的值类型),所以 i.first提供对 key 的访问,i.second提供对映射值的访问(在您的情况下是唯一指针)。

关于c++ - unique_ptr 用法 - 类图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16405802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com