[英]C++ map<string, vector<pair<string, string> > > : adding a mapping to an empty vector?
I'm very new to C++ container templates. 我是C ++容器模板的新手。 I have a collection of records .
我有一套记录 。 Each record has a unique name, and a list of field/value pairs.
每个记录都有一个唯一的名称,以及一个字段/值对的列表。 The records will be accessed by name.
记录将按名称访问。 The order of the field/value pairs is important.
字段/值对的顺序很重要。 Hence I've designed it as follows:
因此,我将其设计如下:
typedef string Typecode;
typedef string Fieldname;
typedef string Fieldvalue;
typedef vector<pair<Fieldname, Fieldvalue> > Field_value_pairs;
typedef map<Typecode, Field_value_pairs> Record_map;
Record_map records;
I want to define a method add_record(Typecode) that will add an entry to records with a key of type Typecode and an empty Field_value_pairs vector. 我想定义一个方法add_record(Typecode) ,它将使用Typecode类型的键和空的Field_value_pairs向量向记录添加一个条目。 (At some point later on I will add some or all of the field/value pairs.) But I can't seem to figure out what map<> and vector<> methods to use.
(稍后,我将添加一些或所有字段/值对。)但是我似乎无法弄清楚要使用哪种map <>和vector <>方法。
I think I want to use operator= , as in records["foo_record"] =
. 我想我想使用operator = ,就像在
records["foo_record"] =
。 But what should I assign as the value, to create an "empty vector of pairs"? 但是,我应该分配什么值来创建“成对的空向量”呢?
You should assign as: 您应指定为:
records["foo_record"] = vector<pair<Fieldname, FieldValue> >();
std::vector's default constructor will create an empty vector, and then you can add new values to it using std :: vector的默认构造函数将创建一个空向量,然后您可以使用添加新值
records["foo_record"].push_back(pair<Fieldname, FieldValue>("name", "value"));
Default construct a Field_value_pairs
object and assign it to the new map entry. 默认构造一个
Field_value_pairs
对象,并将其分配给新的地图项。
void add_record( Record_map& records, Typecode const& code )
{
records[code] = Field_value_pairs();
}
Beware that this will overwrite any existing entry for that Typecode
. 请注意,这将覆盖该
Typecode
任何现有条目。 If you want to conditionally add a Typecode
only if one doesn't already exist, use map::find
to determine whether the entry exists. 如果仅在条件
Typecode
不存在时才有条件地添加类型Typecode
,请使用map::find
确定条目是否存在。
void add_record( Record_map& records, Typecode const& code )
{
if( records.find( code ) == records.end() ) {
records[code] = Field_value_pairs();
} else {
// entry exists, do something else
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.