问题
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 :
- 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