本文介绍了如何初始化结构字段std :: map< std :: string,std :: string>称为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用保存在 std :: vector< tokens> 中的某些数据来初始化结构-令牌只是字符串.我的结构是:

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]是block.name,因此只需编写 block.name = tokens [0] 就很简单但是问题是如何初始化一个params字段,假设键是 tokens [i] ,而值是 tokens [i + 1] .提前致谢.问候!

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!

推荐答案

我猜您的令牌"向量包含索引0处的名称作为特殊值,并且所有后续值都是您在参数"中所需的键/值地图.

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.

用不同的措词,奇数索引(1、3、5等)是"params"映射的键,偶数索引(2、4、6等)-除0-是"params"的值地图.

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));
}

使用(tokens.size()-1)作为最大的"i",以确保在"tokens"向量具有键(在奇数索引上)的情况下,不会抛出std :: out_of_range异常),但没有值(在偶数索引上).

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).

使用std :: map :: insert()方法确实会在地图中不存在新键的情况下插入新键/值对.在地图中插入键/值对并在键已经存在的情况下覆盖值的另一种方法是使用 []运算符,如下所示:

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;

附加说明:

  1. 编译器优化应摆脱引用创建的步骤,并将令牌"向量值直接传递给std :: map :: insert()方法,通过创建无用但增加可读性的引用来避免不必要的开销

这篇关于如何初始化结构字段std :: map&lt; std :: string,std :: string&gt;称为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 22:37