首页 > 解决方案 > 如何在 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但它不断给我分段错误。

标签: c++vectorstdvector

解决方案


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

推荐阅读