我的代碼哪里有錯?
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
? ? // 使用vector存儲數字:3、4、8、4
? ? vector<int> vec;
? ? vec.push_back(3);
? ? vec.push_back(4);
? ? vec.push_back(8);
? ? vec.push_back(4);
? ? //循環打印數字
? ??
? ? vector<int>::iterator it=vec.begin();
? ? for(;it != vec.end();it++)
? ? {
? ? ? ? cout<<*it<<endl;
? ? }
? ? cout<<endl;
? ??
? ? // 使用map來存儲字符串鍵值對
? ? map<string,string> m;
? ? pair<string,string> p1("a","hello");
? ? pair<string,string> p2("b","boy");
? ? pair<string,string> p3("c","cool");
? ? m.insert(p1);
? ? m.insert(p2);
? ? m.insert(p3);
? ?cout<<m.size();
? /* for(int i=0;i<m.size();i++)
? ?{
? ? ? ?cout<<m[i].first<<endl;
? ?}
? ?*/
? ?map<string,string>::iterator it = m.begin();
? ?
? ? // 打印map中數據
? ??
? ?for(;it != m.end();it++)
? ? {
? ? ? ? cout<<it->first<<endl;
? ? ? ? cout<<it->second<<endl;
? ? ? ? cout<<endl;
? ? }
??
? ? return 0;
}
2019-08-21
向量和容器中迭代器的命名重復了,都是it,得換掉。
2018-10-17
你的迭代器 it 重復定義了兩次
后面的it改為it1就不會出錯了
map<string, string>::iterator it1 = m.begin();
// 打印map中數據
for (; it1 != m.end(); it1++)
{
cout << it1->first << endl;
cout << it1->second << endl;
cout << endl;
}