C++ 动态结构体数组与map

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值