C++ 错误:与';不匹配;操作员[]和#x27;在&书信电报;接近匹配>;
未能在gcc 4.1.2/RedHat 5中编译:C++ 错误:与';不匹配;操作员[]和#x27;在&书信电报;接近匹配>;,c++,C++,未能在gcc 4.1.2/RedHat 5中编译: #include <string> #include <vector> #include <map> class Toto { public: typedef std::string SegmentName; }; class Titi { public: typedef Toto::SegmentName SegmentName; // import this type in our n
#include <string>
#include <vector>
#include <map>
class Toto {
public:
typedef std::string SegmentName;
};
class Titi {
public:
typedef Toto::SegmentName SegmentName; // import this type in our name space
typedef std::vector<SegmentName> SegmentNameList;
SegmentNameList segmentNames_;
typedef std::map<SegmentName, int> SegmentTypeContainer;
SegmentTypeContainer segmentTypes_;
int getNthSegmentType(unsigned int i) const {
int result = -1;
if(i < segmentNames_.size())
{
SegmentName name = segmentNames_[i];
result = segmentTypes_[ name ];
}
return result;
}
};
#包括
#包括
#包括
托托班{
公众:
typedef std::字符串段名称;
};
提提班{
公众:
typedef Toto::SegmentName SegmentName;//在名称空间中导入此类型
typedef std::向量段名称列表;
分段名称列表分段名称;
typedef std::map SegmentTypeContainer;
分段类型容器分段类型;
int getNthSegmentType(无符号int i)常量{
int结果=-1;
如果(i
错误是:
error: no match for 'operator[]' in '(...)segmentTypes_[name]'
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:340:
note: candidates are: _Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
[with _Key = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = int, _Compare = std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> >]
错误:“(…)segmentTypes_u[name]”中的“operator[]”不匹配
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../../../../../include/c++/4.1.2/bits/stl_-map.h:340:
注:候选项为:_Tp&std::map::operator[](const _Key&)
[with _Key=std::basic_string,_Tp=int,_Compare=std::less,_Alloc=std::allocator]
为什么??地图相当直观。我想这和typedefs有关,但有什么不对呢?
[编辑]即使我删除所有的
typedef
并在任何地方使用std::string
,问题仍然存在。。。我是否误用了映射?std::map::operator[]
是非常量的,您试图从const
方法使用它
您可以使用std::map::find
,它返回一个const\u迭代器
:
SegmentTypeContainer::const_iterator iter = segmentTypes_.find(name);
如果您使用的是C++11,还可以使用std::map::at
,如果在映射中找不到键,则会引发异常:
result = segmentTypes_.at(name);
std::map::operator[]
不是const
方法,但您是从类的const
方法调用它的。这样做的原因是,如果键不存在,它会添加一个元素
您可以使用C++11at()
:
或者使用std::map::find
SegmentTypeContainer::const_iterator it = segmentTypes_.find(name);
if (it != segmentTypes_.end())
{
// OK, element with key name is present
result = it->second;
}
在C++之前我很确定“存在”。11@Saage仅作为扩展。现在它是标准的。谢谢!我错过了5行+错误消息中的
const
。幸运的是,map.at()
在gcc 4.1.2中可用。
SegmentTypeContainer::const_iterator it = segmentTypes_.find(name);
if (it != segmentTypes_.end())
{
// OK, element with key name is present
result = it->second;
}