考虑一下std::map<const char *, MyClass*>
.
如何访问MyClass
地图指向的对象的成员(变量或函数)?
// assume MyClass has a string var 'fred' and a method 'ethel'
std::map<const char*, MyClass*> MyMap;
MyMap[ "A" ] = new MyClass;
MyMap.find( "A" )->fred = "I'm a Mertz"; // <--- fails on compile
MyMap.find( "A" )->second->fred = "I'm a Mertz"; // <--- also fails
Run Code Online (Sandbox Code Playgroud)
编辑 - 根据Xeo的建议
我发布了虚拟代码.这是真正的代码.
// VarInfo is meta-data describing various variables, type, case, etc.
std::map<std::string,VarInfo*> g_VarMap; // this is a global
int main( void )
{
// ........ g_VarMap["systemName"] = new VarInfo;
g_VarMap.find( "systemName" ).second->setCase( VarInfo::MIXED, VarInfo::IGNORE );
// .....
}
Run Code Online (Sandbox Code Playgroud)
错误是:
struct std::_Rb_tree_iterator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, VarInfo*> >’ has no member named ‘second’
Field 'second' could not be resolved Semantic Error make: *** [src/ACT_iod.o] Error 1 C/C++ Problem
Method 'setCase' could not be resolved Semantic Error –
Run Code Online (Sandbox Code Playgroud)
std::map
将类型内部存储为a std::pair
,并std::map::find
返回一个iterator
.因此,要访问您班级的成员,您必须通过iterator
,其中显示key_type
as first
和value_type
as second
.此外,正如其他人所说,你可能不应该使用const char*
你的key_type
.这是一个简短的例子.
#include <string>
#include <map>
#include <iostream>
struct T
{
T(int x, int y) : x_(x), y_(y)
{}
int x_, y_;
};
int main()
{
typedef std::map<std::string, T> map_type;
map_type m;
m.insert(std::make_pair("0:0", T(0,0)));
m.insert(std::make_pair("0:1", T(0,1)));
m.insert(std::make_pair("1:1", T(1,1)));
// find the desired item (returns an iterator to the item
// or end() if the item doesn't exist.
map_type::const_iterator t_0_1 = m.find("0:1");
if(m.end() != t_0_1)
{
// access via the iterator (a std::pair) with
// key stored in first, and your contained type
// stored in second.
std::cout << t_0_1->second.x_ << ':' << t_0_1->second.y_ << '\n';
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5322 次 |
最近记录: |