c++ - 在 C++ 中显示字符串、vector<int> 映射

标签 c++ dictionary

我有以下 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/

相关文章:

c++ - ppoll 中的信号未立即处理

c++ - 将图像转换为有限大小的调色板的好算法是什么

c++ - 如何在 QWindow 上启用鼠标跟踪

c++ - _mm_comieq_ss Clang 和 GCC 之间的区别

c++ - ROS使用模板类成员作为主题订阅的回调

swift - 巨大的Dictionary对象时编译错误。打破表达

python - 该问题要求根据字典检查列表并在列表中未出现在字典中的项目之前添加 *

c# - 具有不同类型 : Cleaner, 非字符串方法名称的委托(delegate)的 Dictionary<T,Delegate>?

Python-csv-错误 : Sequence Expected

python - 过滤列表中的最新项目