我有以下 map :
std::map<std::string, std::vector<int> > my_map;
我以这种方式在我的 map 中插入键和值:
my_map.insert( std::pair<std::string, std::vector<int> >(nom,vect) );
如何打印 map 的键和值?
我已经测试过了:
for( std::map<std::string, std::vector<int> >::iterator ii=my_map.begin(); ii!=my_map.end(); ++ii)
{
std::cout << (*ii).first << ": " << (*ii).second << std::endl;
}
但由于某种原因我得到这个错误:
error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘std::vector<int>’)
std::cout << (*ii).first << ": " << (*ii).second << std::endl;
最佳答案
首先,使用typedef
(或更现代的方法using
):
typedef std::vector<int> ivector;
typedef std::map<std::string,ivector> sivmap;
sivmap my_map;
// now benefits of using synonyms
my_map.insert( sivmap::value_type(nom,vect) );
// or even easier
my_map.insert( std::make_pair(nom,vect) );
// for loop is less verbose as well
// when there is no intention to modify data use const_iterator
for( sivmap::const_iterator ii=my_map.begin(); ii!=my_map.end(); ++ii)
{
std::cout << ii->first << ": " << ii->second << std::endl;
}
现在让你的循环工作创建运算符
std::ostream &<<( std::ostream &out, const ivector &iv )
{
out << '[';
for( ivector::const_iterator it = iv.begin(); it != iv.end(); ++it ) {
if( it != iv.begin() ) out << ", ";
out << *it;
}
return out << ']';
}
这不仅会让你的代码更短、更简洁,而且更不容易出错,更容易阅读和修改
关于c++ - 在 C++ 中显示字符串、vector<int> 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40933324/