Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

algorithm - Replacing a range between two iterators in C++

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 

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

Output:

{1, 2, 3, 4, 5, 6, 7}
{6, 6, 3, 5, 4, 13, 99}
{6, 3, 5, 4, 5, 6, 7}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...