Unique_ptr use - class map

Can someone help me with the code below to display the contents of a class object?

Q1 - can anyone confirm - if this is the right way to save a pointer to a table class object on a map?

Q 2 - How to display the contents of the entire record on the map?

thanks

#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 
+4
source share
1 answer

Q1 - can anyone confirm - if this is the right way to save a pointer to a table class object on a map?

Yes, this is the correct way to store unique_ptr in a container. Unique pointers are not copied, so you need std::move() when passing it to a function - and you do it.

Q 2 - How to display the contents of the entire record on the map?

If I am missing something obvious, you have actually done the most difficult 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; } 

An iterator is an iterator for std::pair<const int, std::unique_ptr<Table>> (which is a type of map value), therefore i.first provides access to the key, and i.second provides access to the displayed value (a unique pointer in your case).

+4
source

Source: https://habr.com/ru/post/1479416/


All Articles