早期宣布一张地图:
map<char*,char*> rtable; // used to store routing information
现在我正在尝试显示地图的内容:
void Routes::viewroutes(){
typedef map<char*, char*>::const_iterator iter;
for (iter=rtable.begin(); iter != rtable.end(); ++iter) {
cout << iter->second << " " << iter->first << endl;
}
}
收到错误“在'!''标记之前预期的primary-expression和' - &gt;'似乎无法理解我在这里犯的错误。有什么想法吗?
答案 0 :(得分:4)
iter
是代码中的一种类型。应该是变量。
typedef map<char*,char*> my_map_t; // alias for a specialized map
// declare a variable of needed type
my_map_t rtable;
// declare iter of type my_map_t::const_iterator
for (my_map_t::const_iterator iter=rtable.begin(); iter != rtable.end(); ++iter) {
cout << iter->second << " " << iter->first << endl;
}
// scope of the iter variable will be limited to the loop above
答案 1 :(得分:1)
删除typedef。您没有使用该语句声明变量,您正在定义类型然后分配给它。这就是错误。
答案 2 :(得分:1)
声明类型为iter
的变量:
void Routes::viewroutes(){
typedef map<char*, char*>::const_iterator iter;
for (iter i =rtable.begin(); i != rtable.end(); ++i) {
cout << i->second << " " << i->first << endl;
}
}
只是为了好玩:),您可以使用我编写的以下函数将地图或多图的内容流式传输到任何标准流,无论它是标准输出还是文件流。它处理所有类型的流,例如cout或wcout:
template <class Container, class Stream>
Stream& printPairValueContainer(Stream& outputstream, const Container& container)
{
typename Container::const_iterator beg = container.begin();
outputstream << "[";
while(beg != container.end())
{
outputstream << " " << "<" << beg->first << " , " << beg->second << ">";
beg++;
}
outputstream << " ]";
return outputstream;
}
template
< class Key, class Value
, template<class KeyType, class ValueType, class Traits = std::less<KeyType>,
class Allocator = std::allocator<std::pair<const KeyType, ValueType> > >
class Container
, class Stream
>
Stream& operator<<(Stream& outputstream, const Container<Key, Value>& container)
{
return printPairValueContainer(outputstream, container);
}
答案 3 :(得分:-4)
我总是像我这样访问我的地图迭代器(* iter).first和(* iter).second。