STL:访问已作为第二对添加到映射的结构中的数据

STL: Accessing data from a structure that has been added as the second pair to a map

本文关键字:映射 添加 结构 数据 访问 STL      更新时间:2023-10-16

我有一个这样的地图:

typedef std::map<std::string, Copied_Instrument_Data> InternalIdWise_Copied_Instrument_Data;

其中,Copied_Instrument_Data为结构体:

typedef struct 
{
    std::string type;
    std::string marketListId;
    std::string sectorCode;
    std::string validToDate;
    int notificationType;
    bool npgFlag;
}Copied_Instrument_Data;

我使用将数据插入地图

InternalIdwise_Copied_Instrument_Data__Map.insert( std::pair<std::string, Copied_Instrument_Data >(internalId, CID) );

其中CID是Copied_Instrument_Data结构变量。

后来我使用了:iter = InternalIdwise_Copied_Instrument_Data__Map.find("SomeKeyString");

在像这样声明iter之后:InternalIdWise_Copied_Instrument_Data::iterator iter;

然后我有:

if (iter != InternalIdwise_Copied_Instrument_Data__Map.end() )
        Instrument_available = true;
if (Instrument_available == true)
{
        ins_todate = *(iter).second.validToDate;
       std::cout<<ins_todate; 
}

无论如何,这是行不通的。我在ins_todate中没有得到任何数据。

所以,我的问题是:

如何正确访问该元素?

这与运算符优先级有关:

ins_todate = *(iter).second.validToDate;

iter.second.validToDate上使用去引用运算符(去引用(*(运算符的优先级低于元素选择(.(运算符(。

你应该做

ins_todate = (*iter).second.validToDate;

ins_todate = iter->second.validToDate;

不是答案,而是对这里的编码风格的一些建议:

I。如果你在写C++,你应该这样做:

struct Copied_Instrument_Data
{
    ...
};

而不是

typedef struct 
{
    ...
} Copied_Instrument_Data;

后者给出一个未命名的struct,然后是typedef,这是不必要的,并且不能在此struct上使用前向声明。

II。你可以使用std::make_pair在地图中插入元素,我个人认为它更清晰、更容易:

Map.insert( std::make_pair(internalId, CID) );

III。如果临时变量只是一个标志,即,则应替换它

if (iter != InternalIdwise_Copied_Instrument_Data__Map.end() )
        Instrument_available = true;
if (Instrument_available == true)
{
    ...
}

应该是

if (iter != InternalIdwise_Copied_Instrument_Data__Map.end())
{
    ...
}

或者,这可以通过返回调用来排除错误条件:

if (iter == InternalIdwise_Copied_Instrument_Data__Map.end())
{
    // print some error log?
    return;
}
// continue your work!

(您可以参考重构:压印现有代码的设计,第二版,项目6.3内联温度(

希望能有所帮助!:(