3

Javascript のスプライスのような C++ の同様のメソッド/関数はありますか?

W3School の例:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,1,"Lemon","Kiwi");

果物の結果は次のようになります: バナナ、オレンジ、レモン、キウイ、マンゴー

C ++で同じことをしたくありません。クリックすると 1 つずつ消えるボックスの配列を作成しました。やり方がわかりません、助けてください。

PS。SDL ライブラリと Microsoft Visual C++ 2010 Express を使用しています。

4

2 に答える 2

1

ベクターを使用している場合は、次のinsertメソッドにアクセスできます。

#include <vector>
#include <iostream>
#include <string>

int main()
{
    std::vector<std::string> fruits = {"Banana", "Orange", "Apple", "Mango"};
    auto pos = fruits.begin() + 2;

    fruits.insert(pos, {"Lemon", "Kiwi"});

    for (auto fruit : fruits) std::cout << fruit << " ";
}

出力: バナナ オレンジ レモン キウイ アップル マンゴー

ここにデモがあります。

于 2013-06-18T22:34:25.780 に答える
1

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 バージョンと同じように動作しますが、ここで最初のパラメーターとしてベクターを渡す必要があります。

于 2013-06-18T22:42:08.453 に答える