简体   繁体   中英

How to replace a sequence in vector

Let's assume that I have the following vector:

std::vector<int> data{0,1,2,3,4};

I would like to replace the sequence {1,2,3} with a single number. I have found an example with std::replace but there a single number is replaced with other single number. How to replace a sequence in vector ?

We can do this using std::vector::erase(const_iterator first, const_iterator last) as follows. The following function replace the value of org[start] to val and then erases the elements in the range [start+1, end] :

DEMO

template<class T>
std::vector<T> replace(
    const std::vector<T>& org, 
    std::size_t start, 
    std::size_t end, 
    const T& val)
{
    assert(start <= end);
    assert(end < org.size());

    auto vec(org);
    auto it_s = vec.begin() + start;
    *it_s = val;

    vec.erase(it_s + 1, vec.begin() + end + 1);

    return vec;    
}

I've generalized your question into any STL container by using iterator pairs instead of vectors for input. The algorithm has 3 steps:

  1. Find sequence via std::search . Return last if it is not found
  2. Replace first sequence item with new value
  3. Remove remaining items with std::remove_if

As iterators cannot really erase items from container, data.erase(newEnd, data.end()); call is needed to shrink vector.

Algorithm should be quite stable and work even for 1-element vectors. Function can be declared constexpr since C++14.

#include <algorithm>
#include <iostream>
#include <vector>

template <class ForwardIt1, class ForwardIt2, class Value>
constexpr ForwardIt1 replaceSequenceWithValue(ForwardIt1 first, ForwardIt1 last, 
                                              ForwardIt2 s_first, ForwardIt2 s_last,
                                              Value &&value) {
  auto seq_start = std::search(first, last, s_first, s_last);
  if (seq_start == last)
    return last; // return last if no seq was found

  *seq_start = std::forward<Value>(value);

  auto itemsToBeRemoved = std::distance(s_first, s_last) - 1;

  // return new end
  if (itemsToBeRemoved > 0)
    return std::remove_if(std::next(seq_start), last,
                          [&itemsToBeRemoved](const auto &) { return itemsToBeRemoved-- > 0; });
  return last;
}


int main() {
  std::vector<int> data{0, 1, 2, 3, 4};
  std::vector<int> seq{1, 2, 3};
  auto newEnd = replaceSequenceWithValue(data.begin(), data.end(), seq.begin(), seq.end(), 5);
  data.erase(newEnd, data.end());
  for (auto d : data) {
    std::cout << d << '\n';
  }
}

If you don't need such generalization you can wrap it into function with simpler signature:

template <class Value>
constexpr void replaceSequenceWithValue(std::vector<Value> &data, const std::vector<Value> &sequence, Value &&value) {
  auto newEnd = replaceSequenceWithValue(data.begin(), data.end(), sequence.begin(),
                                         sequence.end(), std::forward<Value>(value));
  data.erase(newEnd, data.end());
}

And use like:

int main() {
  std::vector<int> data{0, 1, 2, 3, 4};
  replaceSequenceWithValue(data, {1, 2, 3}, 5);
  for (auto d : data) {
    std::cout << d << '\n';
  }
}

First : vector::erase

// erasing from vector
#include <iostream>
#include <vector>

int main ()
{
std::vector<int> myvector;

// set some values (from 1 to 10)
for (int i=1; i<=10; i++) myvector.push_back(i);

// erase the 6th element
myvector.erase (myvector.begin()+5);

// erase the first 3 elements:
myvector.erase (myvector.begin(),myvector.begin()+3);

std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ' ' << myvector[i];
std::cout << '\n';

return 0;
}

Output: myvector contains: 4 5 7 8 9 10

Then : vector::insert

// inserting into a vector
#include <iostream>
#include <vector>

int main ()
{
std::vector<int> myvector (3,100);
std::vector<int>::iterator it;

it = myvector.begin();
it = myvector.insert ( it , 200 );

myvector.insert (it,2,300);

// "it" no longer valid, get a new one:
it = myvector.begin();

std::vector<int> anothervector (2,400);
myvector.insert (it+2,anothervector.begin(),anothervector.end());

int myarray [] = { 501,502,503 };
myvector.insert (myvector.begin(), myarray, myarray+3);

std::cout << "myvector contains:";
for (it=myvector.begin(); it<myvector.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}

Output: myvector contains: 501 502 503 300 300 400 400 200 100 100 100

maybe you can write a custom function, like this:

    vector<int> replace_sequence(const vector<int> in,int start,int end,int replace)
    {
        vector<int> res;
        //check the index value
        if(start<0 || end > in.size() || start > end){
            return res;
        }
        int distance = end -start;
        //construct the result
        for(int i=0;i<in.size();i++){
            if(i==start){
                res.push_back(replace);
                i+=distance;
            }else{
                res.push_back(in[i]);
            }
        }
        return res;
    }
bool erase_replace_seq (vector <int>& data, int start, int end, int replace)
{
    bool result = false;
if ((start<data.size () && start>=0)  && (end < data.size () && end >=0 && end >= start))
    {
        auto iter = data.erase (data.begin () + start, data.begin () + end);
        data.insert (iter, replace);
        result = true;
    }

    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM