How to initialize a structure field std::map<std::string, std::string> called params

爷,独闯天下 提交于 2021-02-11 12:01:39

问题


I'm trying to initialize a structure using some data being held in a std::vector<tokens> - tokens are simply strings. My struct is:

struct parsedBlock{
std::string name;
std::map<std::string, std::string> params;
} 

parsedBlock block;

tokens[0] is block.name so it's simple to just write block.name = tokens[0] But the question is how to intialize a params field supposing that key is tokens[i] and value is tokens[i+1]. Thanks in advance. Greetings!


回答1:


I guess your "tokens" vector contains the name at index 0 as a special value, and all successive values are the keys/values you want in the "params" map.

Worded differently, odd indexes (1, 3, 5, etc.) being keys of the "params" map, and even indexes (2, 4, 6, etc.) - except 0 - being values of the "params" map.

Assuming your "tokens" vector is correct, you can do something like this :

for (int i = 1; i < (tokens.size() - 1); i += 2) {
    std::string& key = block.params[i];
    std::string& value = block.params[i + 1];
    block.params.insert(std::pair<std::string, std::string>(key, value));
}

Using (tokens.size() - 1), as the maximum "i" can go up to, ensures to not throw a std::out_of_range exception in case the "tokens" vector has a key (on a odd index) but no value (on an even index).

Using std::map::insert() method does insert the new key/value pair only if the key does not already exist in the map. Another way to insert a key/value pair in a map and override the value if the key already exists is to use the [] operator like so :

block.params[key] = value;

Additional notes :

  1. compiler optimization should get rid of the references-creation step, and directly pass "tokens" vector values to the std::map::insert() method, avoiding a superfluous overhead by creating useless-but-increasing-readability references.


来源:https://stackoverflow.com/questions/54113566/how-to-initialize-a-structure-field-stdmapstdstring-stdstring-called-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!