繁体   English   中英

如何打印 std::map <int, std::vector<int> >?</int,>

[英]How to print std::map<int, std::vector<int>>?

以下是我创建map<int, vector<int>>和打印的代码:

//map<int, vector>
map<int, vector<int>> int_vector;
vector<int> vec;
vec.push_back(2);
vec.push_back(5);
vec.push_back(7);

int_vector.insert(make_pair(1, vec));

vec.clear();
if (!vec.empty())
{
    cout << "error:";
    return -1;
}
vec.push_back(1);
vec.push_back(3);
vec.push_back(6);
int_vector.insert(make_pair(2, vec));

//print the map
map<int, vector<int>>::iterator itr;
cout << "\n The map int_vector is: \n";
for (itr2 = int_vector.begin(); itr != int_vector.end(); ++itr)
{
    cout << "\t " << itr->first << "\t" << itr->second << "\n";
}
cout << endl;

打印部分不工作,因为

error: C2678: binary '<<': no operator found which takes a left-hand operand of type 
'std::basic_ostream<char,std::char_traits<char>>' (or there is no acceptable conversion)

map的值( std::map<int, std::vector<int>> )是int向量,并且没有为在std::vector<int>打印std::vector<int>而定义的operator<< 您需要遍历矢量(即地图的值)来打印元素。

for (itr = int_vector.begin(); itr != int_vector.end(); ++itr)
//     ^^ --> also you had a typo here: itr not itr2     
{
    cout << "\t " << itr->first << "\t";
    for(const auto element: itr->second) std::cout << element << " ";
    std::cout << '\n';
}

话虽这么说,如果你有权访问C ++ 11,你可以使用基于范围的for循环 在C ++ 17中,您可以为地图的键值做更直观的结构化绑定声明:

for (auto const& [key, Vec] : int_vector)
{
    std::cout << "\t " << key << "\t";                         // print key
    for (const auto element : Vec) std::cout << element << " ";// print value
    std::cout << '\n';

}

备注 :正如@Jarod42在评论中指出的那样,如果条目事先已知,则可以简化给定代码。

例如,使用std::map::emplace ing:

using ValueType = std::vector<int>;
std::map<int, ValueType> int_vector;
int_vector.emplace(1, ValueType{ 2, 5, 7 });
int_vector.emplace(2, ValueType{ 1, 3, 6 });

或者只是使用std::initializer_list map的std::initializer_list构造函数std::initializer_list std::map

const std::map<int, std::vector<int>> int_vector { {1, {2, 5, 7}}, {2, {1, 3, 6}} };

错误:C2678:二进制'<<':找不到运算符

也意味着您可以编写自己的运算符。 这样做可以很方便,因为您的对象变得更加复杂。

#include <iostream>
#include <vector>
#include <map>

using vector_int_type = std::vector<int>;

std::ostream& operator << (std::ostream& os, const vector_int_type& vect) {
    for (const auto& i : vect)
        os << '\t' << i;
    return os;
}

int main()
{
    std::map<int, vector_int_type> int_map;
    int_map[1] = vector_int_type{ 1,2,3 };
    int_map[2] = vector_int_type{ 4,5,6 };

    for (auto& item : int_map)
        std::cout << item.first << " is: " << item.second << std::endl;
}

打印 map<int, vector<'int'> > mp;

 for(auto it: mp){
     cout<<it.first<<" ";
     for(auto i : it.second){
         cout<<i<<" ";
     }
     cout<<endl;
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM