STL:访问已作为第二对添加到映射的结构中的数据
STL: Accessing data from a structure that has been added as the second pair to a map
我有一个这样的地图:
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内联温度(
希望能有所帮助!:(
相关文章:
- QT通过C++添加映射QML项目
- 添加静态constexpr成员是否会更改结构/类的内存映射
- 无法添加多个键以映射将结构作为键
- 添加要映射的对象的唯一指针
- 将相同的键添加到低序映射
- 在具有 std::p air 键和值的映射中添加 b2vec2
- 添加字符串向量和不同数据类型向量的映射
- 无法将元素添加到 STL 映射
- 将数据添加到现有类,而无需继承、映射或修改类
- C++静态初始化顺序:添加到映射中
- C++构造函数期间向映射添加"self"
- 如何在类中添加结构,结构的向量以映射
- 在向量上迭代,并添加迭代器实际指向的对象作为映射中的键
- 相同的密钥(使用malloc创建)添加了两次映射
- 添加多个元素以映射<pair> c++
- C++ - 使用 lambda 将映射添加到映射
- 向映射c++添加structs
- 向映射添加类
- 尝试向静态映射添加大量元素时出现段故障异常
- 如何为boost融合映射添加boost归档序列化支持