gpt4 book ai didi

c++ - 如何替换某些范围的 std::vector 数据

转载 作者:可可西里 更新时间:2023-11-01 18:28:46 25 4
gpt4 key购买 nike

std::vector<char> v;
v.push_back('a');
v.push_back('b');
v.push_back('c');
v.push_back('d');
v.push_back('e');
v.push_back('f');

char c[3] = { 'z', 'x', 'y' };

// Want to make abzxyf
//v.insert(v.begin() + 2, c, c + 3); // it doesn't work as I wanted.

// Yes it works. but if c is more bigger, it will be crash.
std::copy(c, c + 3, v.begin() + 2);

v.clear();
v.push_back('a');
v.push_back('b');
v.push_back('c');
v.push_back('d');
v.push_back('e');
v.push_back('f');

// If vector needs more memory, I'd let him grow automactically
// So I tried this.(expected abcdezxy)
// But it's result is abcdezxyf. f is still remain.
std::copy(c, c + 3, std::inserter(v, v.begin() + 5));

我应该使用什么算法或方法?

最佳答案

如果 sizeof(c) 更大,在 copy() 之前的 resize() 应该可以解决问题。

例如

if (sizeof(c) + 2 > v.size())
v.resize(sizeof(c) + 2);
// now copy
std::copy(c, c + sizeof(c), v.begin() + 2);

关于c++ - 如何替换某些范围的 std::vector 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6746538/

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