#include <iostream>
#include <map>
struct test {
std::string str1;
std::string str2;
};
int main() {
std::map<std::string, test*> mymap;
mymap["one"] = new test[8]; // 申请内存
mymap["one"][0].str1 = "test 1";
mymap["two"] = new test[8];
mymap["two"][0].str1 = "test 2";
std::map<std::string, test*>::iterator iter; // 遍历
for (iter = mymap.begin(); iter != mymap.end(); iter++) {
std::cout << iter->first << std::endl;
std::cout << iter->second[0].str1 << std::endl;
delete[] iter->second; // new[]一定要释放
}
return 0;
}
不建议使用上面指针的方式,应该和 std::vector 结合起来使用,能不使用new和delete就不要使用
#include <iostream>
#include <map>
#include <vector>
struct test {
std::string str1;
std::string str2;
};
int main() {
std::map<std::string, std::vector<test>> mymap;
test cTest1;
cTest1.str1 = "t1 str1";
cTest1.str2 = "t1 str2";
mymap["one"].push_back(cTest1);
test cTest2;
cTest2.str1 = "t2 str1";
cTest2.str2 = "t2 str2";
mymap["two"].push_back(cTest2);
std::map<std::string, std::vector<test>>::iterator iter; // 遍历
for (iter = mymap.begin(); iter != mymap.end(); iter++) {
std::cout << iter->first << std::endl;
std::cout << iter->second[0].str1 << std::endl;
}
return 0;
}