if(tmp_init_save_port != init_save_port.end()){ //show_port_list = (tmp_init_save_port->second[0])[tmp_id]; cnt=snprintf(p->outbuffer,sizeof(p->outbuffer),"\"applyObj\":\"%s\",", ""); cyg_httpd_write_chunked(p->outbuffer, cnt); cnt=snprintf(p->outbuffer,sizeof(p->outbuffer),"\"applyVal\":\"%s\",", ""); cyg_httpd_write_chunked(p->outbuffer, cnt); }else if(tmp_init_save_vlan != init_save_vlan.end()) { cnt=snprintf(p->outbuffer,sizeof(p->outbuffer),"\"applyObj\":\"%s\",", "vlan"); cyg_httpd_write_chunked(p->outbuffer, cnt); cnt=snprintf(p->outbuffer,sizeof(p->outbuffer),"\"applyVal\":\"%u\",", tmp_init_save_vlan->second[0]); cyg_httpd_write_chunked(p->outbuffer, cnt); }else { cnt=snprintf(p->outbuffer,sizeof(p->outbuffer),"\"applyObj\":\"%s\",", ""); cyg_httpd_write_chunked(p->outbuffer, cnt); cnt=snprintf(p->outbuffer,sizeof(p->outbuffer),"\"applyVal\":\"%s\",", ""); cyg_httpd_write_chunked(p->outbuffer, cnt); }优化下这个代码
时间: 2023-08-02 07:11:02 浏览: 84
您可以优化这段代码,使用一个共同的代码块来处理重复的部分,然后根据不同的条件进行不同的处理。以下是优化后的代码示例:
```cpp
// 共同的代码块
cnt = snprintf(p->outbuffer, sizeof(p->outbuffer), "\"applyObj\":\"%s\",", "");
cyg_httpd_write_chunked(p->outbuffer, cnt);
cnt = snprintf(p->outbuffer, sizeof(p->outbuffer), "\"applyVal\":\"%s\",", "");
cyg_httpd_write_chunked(p->outbuffer, cnt);
// 根据条件进行处理
if (tmp_init_save_port != init_save_port.end()) {
// 处理 tmp_init_save_port 条件
} else if (tmp_init_save_vlan != init_save_vlan.end()) {
cnt = snprintf(p->outbuffer, sizeof(p->outbuffer), "\"applyObj\":\"%s\",", "vlan");
cyg_httpd_write_chunked(p->outbuffer, cnt);
cnt = snprintf(p->outbuffer, sizeof(p->outbuffer), "\"applyVal\":\"%u\",", tmp_init_save_vlan->second[0]);
cyg_httpd_write_chunked(p->outbuffer, cnt);
} else {
// 处理其他条件
}
```
通过将重复的部分提取出来,可以减少代码冗余,并提高可读性和维护性。请根据您的具体需求对代码进行适当调整和修改。
阅读全文