닫기

Initialize std::map

image

I would like to make the initialization code for the C++ std::map instance (table in the example below) a little more clean. Please lend me your wisdom.

Please use C++17.

Using a std::stringstream that can conveniently handle an enum called magic_enum, a static instance of std::map (table in the example below) is initialized in a dirty manner from a global function (trash::initialize() in the example below). I would like to write it using a constructor and an initialization list, but it is somehow difficult, so please tell me how to write it.

using namespace std pollutes global namespace and leads to possible conflicts with other functions. Why is "using namespace std" considered bad practice?

I would like to write it using a constructor and an initialization list

Why don't you just write a function:

using namespace std pollutes global namespace and leads to possible conflicts with other functions. Why is "using namespace std" considered bad practice?

A std::initialiser_list can only be initialised from a braced-init-list (or copied from another std::initialiser_list), you can't turn some other container into one.

You can use std::ranges::to to initialise a map from a range of pairs, and you can use std::views::transform to make your pairs from a range of enums, which magic_enum can provide

std::format is a type-safe replacement for printf, fixing one of the major warts of C++ formatting. You don't need to use a stringstream.

Which ends up like this:

How about something like this using iterator?

AI에게 물어보기
#1 #2 #3 #4 #5 #6 #7 #8 #9 #10 #11 #12 #13 #14 #15 #16 #17 #18 #19 #20 #21 #22 #23 #24 #25 #26 #27 #28 #29 #30 #31 #32 #33 #34 #35 #36 #37 #38 #39 #40 #41 #42 #43 #44 #45 #46 #47 #48 #49 #50 #51 #52 #53 #54 #55 #56 #57 #58 #59 #60 #61 #62 #63 #64 #65 #66 #67 #68 #69 #70 #1 #2 #3 #4 #5 #6 #7 #8 #9 #10 #11 #12 #13 #14 #15 #16 #17 #18 #19 #20 #21 #22 #23 #24 #25 #26 #27 #28 #29 #30 #31 #32 #33 #34 #35 #36 #38 #39 #41 #42 #43 #44 #45 #46 #47 #48 #49 #50 #51 #53 #56 #58 #60 #62 #63 #67 #68 #70
어플전용 할인코드 호텔 8% 할인
선착순 마감 [아고다]
AGODADEAL8
클릭하면 자동복사
전세계 호텔 15% 할인코드
선착순 마감 [아고다]
AGODASPONSORED
클릭하면 자동복사