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

发布于 2024-11-25 12:35:42 字数 733 浏览 0 评论 0原文

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

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

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

What algorithm or method should I use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

海拔太高太耀眼 2024-12-02 12:35:43

如果 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);

If the sizeof(c) is bigger, resize() before the copy() that should do the trick.

e.g.

if (sizeof(c) + 2 > v.size())
  v.resize(sizeof(c) + 2);
// now copy
std::copy(c, c + sizeof(c), v.begin() + 2);
彼岸花似海 2024-12-02 12:35:43

如果你想进行文本处理,你可以考虑使用具有 replace 功能的 std::string

std::vector 没有。您必须将覆盖成员与inserterase 结合使用。

If you want to do text processing, you might consider using std::string which has replace functions.

std::vector does not. You have to use the appropriate combination of overwriting members combined with insert and erase.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文