gpt4 book ai didi

c++ - 我如何复制二维 vector C++ 中的元素并将其放在原始元素旁边

转载 作者:搜寻专家 更新时间:2023-10-31 02:05:05 26 4
gpt4 key购买 nike

std::vector<std::vector<char> > fog { { 'a', 'b', 'c'  },
{ 'f', 'g', 'a' } };

上面的 vector 应该变成雾

{ { 'a', 'a', 'b','b', 'c', 'c'  }, { 'f', 'f','g', 'g', 'a' 'a' } };

我已经尝试使用 std::vectorinsert() 方法,但它一直给我段错误。

最佳答案

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

*) 因为如果 vector 必须增长到超出其容量,它将使所有迭代器失效。

使用 insert() 的返回值可以在没有 reserve() 的情况下完成:

for (auto &v : fog) {
for (auto it = v.begin(); it != v.end(); ++it)
it = v.insert(it + 1, *it);
}

关于c++ - 我如何复制二维 vector C++ 中的元素并将其放在原始元素旁边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52509623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com