vector<string> "alle nicht-double elemente entfernen"
-
hallo,
vector<string>::iterator it; it = remove_if(eingang.begin(),eingang.end(),bind2nd(not_equal_to<double>(), 0));ich möchte aus meinem vector<string> alle elemente entfernen die nicht_numerisch sind, sprich int oder double.
geht das nicht mit "not_equal_to" ?
greez + thx
grizzel
-
grizzzel schrieb:
geht das nicht mit "not_equal_to" ?
not_equal_to<T> vergleicht zwei *Werte* vom Typ T. Es konvertiert nicht einen Wert vom Typ Y in den Typ T und vergleicht dann.
Du brauchst mehr sowas:
struct IsNum : std::unary_function<bool, std::string> { bool operator()(const std::string& s) const { char* e; strtod(s.c_str(), &e); return e == s.c_str() + s.length(); } };
-
geht das nicht mit "remove_if" ?
ich dachte so:remove_if(beginn,end,<wenn nicht numerisch>)
...
-
grizzzel schrieb:
geht das nicht mit "remove_if" ?
ich dachte so:remove_if(beginn,end,<wenn nicht numerisch>)
...
remove_if ist nur der Algorithmus. Entscheidend ist hier das Prädikat.
// Achtung: In der ersten Variante hatte ich Argument- und Return-Type vertauscht. struct IsNum : std::unary_function<std::string, bool> { bool operator()(const std::string& s) const { char* e; strtod(s.c_str(), &e); return e == s.c_str() + s.length(); } }; int main() { std::vector<string> v; v.push_back("Hallo"); v.push_back("123"); v.push_back("17.86"); v.push_back("Welt"); v.erase(std::remove_if(v.begin(), v.end(), std::not1(IsNum())), v.end()); std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n")); }