I want to clean the initialization of std::map

Asked 1 years ago, Updated 1 years ago, 213 views

I would like to make the initialization code of the instance of std::map of C++ (in the example below::table) a little cleaner.
Please lend me your wisdom.
*C++17 please

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

It doesn't matter if the type and data increase, or if you can use it the same way, it doesn't have to be std::map (but I don't want to increase dependency if possible).

add
(For other purposes): The logic that generates the first member value of the element in the table may change in the future, and please write it in a way that will still be useful.

Code

#include<iostream>
# include <map>
# include <sstream>
# include <iomanip>
# include "magic_enum.hpp" // https://github.com/Neargye/magic_enum/releases/download/v0.8.1/magic_enum.hpp
using namespace std;
enum TCPSTATUS {
    UNKNOWN, ESTABLISHED, SYN_SENT, SYN_RECV, FIN_WAIT1, FIN_WAIT2, TIME_WAIT, CLOSE, CLOSE_WAIT, LAST_ACK, LISTEN, CLOSING,
};
map<string, TCPSTATUS>table;
namespace crash {
    void*initialize(){
        magic_enum::enum_for_each<TCPSTATUS>([&](autoval){
            constexpr TCPSTATUS status=val;
            US>stringstream s;
            ss<hex<<uppercase<<setw(2)<setfill('0')<magic_enum::enum_integer(status);
            table [ss.str()] = status;
        });
        return nullptr;
    }
    void*dummy=initialize();
}
int main(intargc, char*argv[]){
    for (const auto&p:table) {
        cout<<p.first<"->"<magic_enum::enum_name(p.second)<endl;
    }
    return 0;
}
00->UNKNOWN
01 - > ESTABLISHED
US>02->SYN_SENT
03->SYN_RECV
04->FIN_WAIT1
05->FIN_WAIT2
06->TIME_WAIT
07 - > CLOSE
08 - > CLOSE_WAIT
09->LAST_ACK
0A->LISTEN
0B->CLOSING

c++

2022-10-25 11:42

1 Answers

inline variable when it comes to within the C++17 range

static inline auto constable=[]{
    std::map<std::string, TCPSTATUS>table;
    for(autoe:magic_enum::enum_values<TCPSTATUS>()){
        std::stringstreams;
        ss<<std::hex<<std::uppercase<<std::setw(2)<<std::setfill('0')<e;
        table [ss.str()] = e;
    }
    return table;
}();

That's about it. If you can use C++20's std::format(),

static inline auto constable=[]{
    std::map<std::string, TCPSTATUS>table;
    for(autoe:magic_enum::enum_values<TCPSTATUS>())
        table [std::format("{:02X}", int(e))] = e;
    return table;
}();

It's easier.


2022-10-25 11:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.