![](/img/trans.png)
[英]How to use std::map to retrive a std::vector<int> in c++?
[英]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.