我如何复制二维向量 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' } };
我已经尝试使用 std::vector
的 insert()
方法,但它一直给我分段错误。
#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()
的 return 值可以在没有 reserve()
的情况下完成:
for (auto &v : fog) {
for (auto it = v.begin(); it != v.end(); ++it)
it = v.insert(it + 1, *it);
}
std::vector<std::vector<char> > fog { { 'a', 'b', 'c' },
{ 'f', 'g', 'a' } };
上面的矢量应该变成雾
{ { 'a', 'a', 'b','b', 'c', 'c' }, { 'f', 'f','g', 'g', 'a' 'a' } };
我已经尝试使用 std::vector
的 insert()
方法,但它一直给我分段错误。
#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()
的 return 值可以在没有 reserve()
的情况下完成:
for (auto &v : fog) {
for (auto it = v.begin(); it != v.end(); ++it)
it = v.insert(it + 1, *it);
}