c vector<bool>

在不清楚vector<bool>的实现逻辑的时候,尽量不要使用,因为里面有些隐藏的问题,会出现不可预期的问题。

首先,vector<bool>不是容器(https://www.zhihu.com/question/23367698/answer/148258487),实现的时候将模版特化了,使用位的方式存储。

另外,性能也很差,和vector其他类型的模版相比,性能相差40倍(参考:https://www.cnblogs.com/wpcockroach/p/3179572.html

尽量使用其他数据结构去替换掉vector<bool>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是完整代码: ```cpp #include <iostream> #include <vector> #include <map> #include <algorithm> using namespace std; struct dat { int val; string name; }; bool cmp(const dat &a, const dat &b) { return a.val < b.val; } map<int, vector<vector<dat>>> merge(vector<dat> vk) { sort(vk.begin(), vk.end(), cmp); map<int, vector<vector<dat>>> vvMap; for (int i = 0; i < vk.size(); i++) { int val = vk[i].val; int j = i; vector<dat> temp; while (j < vk.size() && vk[j].val == val) { temp.push_back(vk[j]); j++; } i = j - 1; map<string, vector<dat>> mp; for (int k = 0; k < temp.size(); k++) { mp[temp[k].name].push_back(temp[k]); } vector<vector<dat>> res; for (auto it = mp.begin(); it != mp.end(); it++) { res.push_back(it->second); } vvMap[val] = res; } return vvMap; } int main() { vector<dat> vk = {{2, "b"}, {3, "a"}, {1, "c"}, {2, "d"}, {3, "c"}, {1, "a"}}; map<int, vector<vector<dat>>> vvMap = merge(vk); for (auto it = vvMap.begin(); it != vvMap.end(); it++) { cout << it->first << ": "; for (int i = 0; i < it->second.size(); i++) { cout << "{"; for (int j = 0; j < it->second[i].size(); j++) { cout << "[" << it->second[i][j].val << ", " << it->second[i][j].name << "]"; if (j != it->second[i].size() - 1) { cout << ", "; } } cout << "}"; if (i != it->second.size() - 1) { cout << ", "; } } cout << endl; } return 0; } ``` 代码说明: 1. 定义结构体 `dat`,包含 `int val` 和 `string name` 两个成员。 2. 定义比较函数 `cmp`,用于按照 `val` 进行排序。 3. 定义函数 `merge`,用于将输入的 `vector<dat>` 按照 `val` 进行排序,并将相同 `val` 的元素合并到一个 `vector` 中,然后将相同 `name` 的元素合并到一个 `vector` 中,最后将结果存储在 `map<int, vector<vector<dat>>>` 中并返回。 4. 在 `main` 函数中定义输入 `vector<dat>`,调用 `merge` 函数并将结果存储在 `map<int, vector<vector<dat>>>` 中,最后输出结果。 输出结果: ``` 1: {[1, c], [1, a]} 2: {[2, b], [2, d]} 3: {[3, a], [3, c]} ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值