在 C++11 中:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<typename T>
vector<T> splice(vector<T>& v, int start, int howmuch, const vector<T>& ar) {
vector<T> result(begin(v) + start, begin(v) + start + howmuch);
v.erase(begin(v) + start, begin(v) + start + howmuch);
v.insert(begin(v) + start, begin(ar), end(ar));
return result;
}
int main() {
vector<string> fruits = {"Banana", "Orange", "Apple", "Mango"};
auto v = splice(fruits, 2, 1, {"Lemon", "Kiwi"});
cout << "Returned value: " << endl;
for (auto &s: v) {
cout << "\t" << s << endl;
}
cout << endl;
cout << "fruits: " << endl;
for (auto &s: fruits) {
cout << "\t" << s << endl;
}
}
产生输出:
Returned value:
Apple
fruits:
Banana
Orange
Lemon
Kiwi
Mango
这是一个模板版本,因此它不仅适用于字符串;函数的行为与 JS 版本相同,但您必须在此处将向量作为第一个参数传递。