मैंने स्ट्रिंग के वेक्टर के माध्यम से चलाने के लिए एक फ़ंक्शन बनाया है और लंबाई 3 या उससे कम की किसी स्ट्रिंग को हटा दिया है। यह एसटीएल एल्गोरिदम पुस्तकालय का उपयोग करने में एक सबक है।मिटाएं() को हटाने के बाद()
मुझे इस बात में परेशानी हो रही है कि कार्य कार्य करते हैं लेकिन न केवल यह लंबाई 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;
}
महान विवरण। क्या हो रहा है यह स्पष्ट करने के लिए बहुत बहुत धन्यवाद! – MCP
यदि 'myVector' खाली था तो यह और भी अधिक काट देगा। फिर 'iter' 'myVector.end()' के बराबर होगा, और' मिटाएं (iter) 'का उपयोग करके मिटाना यूबी की ओर ले जाएगा। – Ruslan