13

文字列のベクトルを実行し、長さが 3 以下の文字列を削除する関数を作成しました。これは、STL アルゴリズム ライブラリの使用に関するレッスンです。

関数が機能するという問題がありますが、長さ3以下の文字列を削除するだけでなく、文字列「ベクター」を最後に追加します。

出力は

This test vector

代わりに

This test vector vector"

どうすれば修正できますか?

/*
* using remove_if and custom call back function, write RemoveShortWords 
* that accepts a vector<string> and removes all strings of length 3 or
* less from it. *shoot for 2 lines of code in functions.
*/

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;

bool StringLengthTest(string test) //test condition for remove_if algo.  
{
    return test.length() <= 3;
}

void RemoveShortWords(vector<string> &myVector)
{
    //erase anything in vector with length <= 3
    myVector.erase(remove_if(myVector.begin(),
                             myVector.end(),
                             StringLengthTest));
}

int main ()
{
    //add some strings to vector
    vector<string> myVector;
    myVector.push_back("This");
    myVector.push_back("is");
    myVector.push_back("a");
    myVector.push_back("test");
    myVector.push_back("vector");

    //print out contents of myVector (debugging)
    copy(myVector.begin(), myVector.end(), ostream_iterator<string>(cout," "));
    cout << endl; //flush the stream

    RemoveShortWords(myVector); //remove words with length <= 3

    //print out myVector (debugging)
    copy(myVector.begin(), myVector.end(), ostream_iterator<string>(cout," "));
    cout << endl;

    system("pause");
    return 0;
}
4

2 に答える 2

31

ステートメントを区切ると、これを理解するのが最も簡単になります。

auto iter(remove_if(myVector.begin(), myVector.end(), StringLengthTest));
myVector.erase(iter);

これらの 2 行は、単一行と同じことを行います。そして、「バグ」が何であるかは明らかです。remove_if、最初に機能します。ベクトル全体を反復し、すべての「選択された」エントリを「最後に」移動します(より適切に言えば、選択されていないエントリを前に移動します)。実行後、残りのエントリの「最後の」位置にイテレータを返します。次のようになります。

この
テスト
ベクトル
test <- イテレータがここを指す
ベクトル

次に、1 つの反復子で消去を実行します。つまり、指定された単一の要素を消去することを意味します。つまり、「テスト」要素を消去します。- 残っているのは、あなたが見ているものです。

これを修正するには、remove_if によって返されたベクトルから end() までを単純に消去します。

myVector.erase(remove_if(myVector.begin(), myVector.end(), StringLengthTest), myVector.end()); //erase anything in vector with length <= 3
于 2012-01-29T14:32:21.210 に答える
12

2 つのパラメーター形式の消去を使用する必要があります。

myVector.erase(remove_if(myVector.begin(), myVector.end(), StringLengthTest),
               myVector.end());
于 2012-01-29T14:28:55.630 に答える