c++ - 如何在 2d 矢量 C++ 中复制一个元素并将其放在原始元素旁边
问题描述
std::vector<std::vector<char> > fog { { 'a', 'b', 'c' },
{ 'f', 'g', 'a' } };
上面的矢量应该变成雾
{ { 'a', 'a', 'b','b', 'c', 'c' }, { 'f', 'f','g', 'g', 'a' 'a' } };
我已经尝试过使用的insert()
方法,std::vector
但它不断给我分段错误。
解决方案
#include <vector>
int main()
{
std::vector<std::vector<char>> fog {
{ 'a', 'b', 'c' },
{ 'f', 'g', 'a' }
};
fog[0].reserve(fog[0].size() * 2); // make sure the vector won't have to grow
fog[1].reserve(fog[1].size() * 2); // during the next loops *)
for (auto &v : fog) {
for (auto it = v.begin(); it != v.end(); it += 2)
it = v.insert(it + 1, *it);
}
}
*) 导致如果向量必须超出其容量,它将使所有迭代器无效。
使用它的返回值insert()
可以不用reserve()
:
for (auto &v : fog) {
for (auto it = v.begin(); it != v.end(); ++it)
it = v.insert(it + 1, *it);
}
推荐阅读
- reactjs - 将对象添加到状态时出现 React.js 错误(使用反应挂钩)
- linux - 如何在linux中使用`mt`命令通过首先将驱动器头移动到一般位置来快速提取磁带驱动器中的文件?
- css - 如何使用 Emotion CSS 函数传递道具
- html - 无法让卡响应移动设备
- python - 如何使用 XArray 合并特定的 netcdf4
- kubernetes - 如何使用 Config Connector 在 GKE 上设置 StorageNotification
- bash - `echo $0` 在 VS Code 中返回完整路径而不是破折号前缀的 shell
- java - 尽管包含了 Jar,但未找到 Java 类
- django - 如何为每个多个用户创建单个配置文件?
- python - 如何在 Google Dataproc 集群中安装和运行 pip