c++里map<string,string>怎么遍历

2025-04-15 15:48:24
推荐回答(3个)
回答1:

这个是不是map里面的string参数? 是的
it->second是map中对应于it->first的vector, 你这样的写法导致了复制,应该用引用。
tmp[i] 是node变量。

下面是一段简化的代码:

#include
#include
#include

struct Point {
int x;
int y;
};

std::ostream & operator <<(std::ostream & out, const Point & p) {
return out << '(' << p.x << ',' << p.y << ')';
}

using ConType = std::map>;

void travel(ConType & con);

int main() {
std::map> con;
std::vector a, b, c;
a.push_back({1, 3});
a.push_back({4, 5});
a.push_back({5, 7});
b.push_back({2, 3});
b.push_back({5, 3});
c.push_back({5, 7});
c.push_back({5, 4});
con["a"] = a;
con["b"] = b;
con["c"] = c;
travel(con);
}

void travel(ConType & con) {
for(auto & i : con) {
for(auto & j : i.second) {
std::cout << j << '\t';
}
std::cout << std::endl;
}
}

回答2:

#include
#include
#include
using namespace std;
int main()
{
map m;
m.insert(pair("小红","1班"));
m.insert(pair("小明", "2班"));
m.insert(pair("小黄", "3班"));
for (map::iterator it = m.begin(); it != m.end(); it++) {
cout << it->first <<"\t"<first] << endl;
}
return 0;
}

回答3:

遍历方法如下:

map mymap;

auto it = mymap.begin();

for(;it != mymap.end();++it)

{

cout << it->first.c_str() << " " << it->second.c_str() << endl;

}