2

我有一张这样的地图:

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

在这样声明之后iterInternalIdWise_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

所以,我的问题是:

如何正确访问该元素?

4

2 回答 2

4

它与运算符优先级有关:

ins_todate = *(iter).second.validToDate;

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

你应该做

ins_todate = (*iter).second.validToDate;

或者

ins_todate = iter->second.validToDate;
于 2013-03-27T15:37:55.007 回答
1

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

I. 如果你正在编写 C++,你应该这样做:

struct Copied_Instrument_Data
{
    ...
};

代替

typedef struct 
{
    ...
} Copied_Instrument_Data;

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

二、您可以使用std::make_pair将元素插入地图,我个人认为它更清晰,更容易:

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

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

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!

(可以参考Refactoring: Impriving the design of existing code, 2nd Ed., Item 6.3 Inline Temp

希望有帮助!:)

于 2013-03-28T02:14:30.647 回答