[英]Display a string, vector<int> map in C++
我有以下地圖:
std::map<std::string, std::vector<int> > my_map;
我以這種方式在地圖中插入鍵和值:
my_map.insert( std::pair<std::string, std::vector<int> >(nom,vect) );
如何打印地圖的鍵和值?
我已經測試過:
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 << ']';
}
這不僅使您的代碼更短,更冗長,而且更不易出錯,更易於閱讀和修改。
好吧,這是因為std::vector<int>
沒有operator<<
,這使它成為一種罕見的C ++編譯錯誤,這種錯誤非常容易理解和簡潔。 就像您使用迭代器為std::map
編寫自己的輸出一樣,您將需要對std::vector
做類似的事情。
該標准對我們不執行此操作的原因之一是人們期望輸出出現的格式種類繁多。例如,如果您希望數據用(
和)
包圍,而每個兩個元素用,
分隔,
和一個空格,作為用戶要求您在幾行中實現它比創建一種算法既允許又要在小數點上對齊並縮進用於矢量的遞歸打印的每行上打印每個元素要容易得多別人可能想要的向量。
出於同樣的原因,建議在需要的地方格式化向量,而不是實際實現和operator<<
。 如果您要對程序中多個點中的相同類型的矢量使用相同的打印機制,並且希望能夠將其很好地編寫為std::cout << vector << '\\n'
,那是最好的方法是創建一個公開擴展std::vector<int>
,如
class printable_vector : public std::vector<int> {
using std::vector<int>::vector; // inherit constructors
// (all other public member functions are inherited automatically)
friend std::ostream& operator<< (std::ostream& os, const printable_vector& vector) {
// do the actual printing to os...
return os;
}
};
這樣,您可以以普通std::vector<int>
任何方式來操作printable_vector
,但它也提供輸出功能。
您需要添加另一個氣泡來解決該問題:
#include <map>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::map<std::string, std::vector<int> > my_map;
string nom = "carlitos";
vector<int> vect;
vect.push_back(1);
vect.push_back(2);
vect.push_back(3);
vect.push_back(4);
my_map.insert( std::pair<std::string, std::vector<int> >(nom,vect) );
for( std::map<std::string, std::vector<int> >::iterator ii=my_map.begin(); ii!=my_map.end(); ++ii)
{
for( std::vector<int>::iterator iii=(*ii).second.begin(); iii!=(*ii).second.end(); ++iii)
{
std::cout << (*ii).first << ": " << *iii << std::endl;
}
}
}
(這是因為std::cout
不會通過運算符<<
直接打印std::vector
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.