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