在C ++中替换两个迭代器之间的范围 [英] Replacing a range between two iterators in C++
本文介绍了在C ++中替换两个迭代器之间的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个非常数迭代器开始和结束.我想用其他两个迭代器之间的值完全替换begin和end之间的范围.我知道使用非常量迭代器,我可以使用以下语法.
Assume I have two non-constant iterators begin and end. I want to completely replace the range between begin and end with values, that are between two other iterators. I know with non-constant iterators I can use the following syntax.
*begin = *result.begin();
*end = *result.end();
但这只会更改开始和结束迭代器后面的值
But this will only change the values behind begin and end iterators
更准确地说.我有一个初始向量
To be more precise. I have an initial vector
{1, 2, 3, 4, 5, 6, 7}
^ ^
begin end
和其他称为result的向量,其中包含
and some other vector called result, which contains
{6, 6, 3, 5, 4, 13, 99}
^ ^
begin end
最后,我希望我的初始数组看起来像
at the end I want my initial array to look like
{6, 3, 5, 4, 5, 6, 7}
推荐答案
使用 <代码> std :: copy() ,可以这样做:
Using std::copy()
, it can be done like this:
#include <iostream>
#include <vector>
#include <algorithm>
void printVector(const std::vector<int>& v) {
bool first = true;
std::cout << '{';
for (int i : v) {
if (!first) std::cout << ", ";
std::cout << i;
first = false;
}
std::cout << "}\n";
}
int main(void) {
std::vector<int> v1 = {1, 2, 3, 4, 5, 6, 7};
std::vector<int> v2 = {6, 6, 3, 5, 4, 13, 99};
printVector(v1);
printVector(v2);
std::vector<int>::iterator dest_begin = v1.begin();
std::vector<int>::iterator src_begin = std::next(v2.begin(), 1);
std::vector<int>::iterator src_end = std::next(v2.begin(), 5);
std::copy(src_begin, src_end, dest_begin);
printVector(v1);
return 0;
}
输出:
{1, 2, 3, 4, 5, 6, 7}
{6, 6, 3, 5, 4, 13, 99}
{6, 3, 5, 4, 5, 6, 7}
这篇关于在C ++中替换两个迭代器之间的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文