如何在 2d 矢量 c++ 中复制元素并将其放在原始元素旁边
How do i duplicate an element in 2d vector c++ and put it next to the original element
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);
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 如何在 2d 矢量 c++ 中复制元素并将其放在原始元素旁边
- 将集合的随机元素添加到列表中,然后将其从原始集合中移除
- 反转由空格分隔的字符串元素将返回比原始字符串更大的字符串
- 固定大小的容器,其中元素被排序,并可以为C 中的数据提供原始指针
- 矢量元素如何在矢量 std::move 之后保留其原始地址
- 访问原始指针的INT矢量元素
- std::排序比较器,可以看到元素的(原始)索引
- 有没有更好的方法来删除对存储在 vector 中的元素的原始指针引用
- 反向链接列表,为什么当不应该时,为什么头仍然指向原始第一个元素
- 查找从数组中删除原始元素的顺序
- 对容器进行排序,然后在保留原始排序的情况下移动元素
- 创建原始图形元素(没有Windows chrome)