c++ - how to improve this code about strtok_r -


I want to remove some tokens from std :: string by delimiter, and write a function as follows, but it is still Errors:

  enum TO_TYPE {TO_INT = 0, TO_FLOAT, TO_STRING}; Template & lt; Typename T & gt; Of vector & lt; T & gt; String_to_token (string and string, const four * delim, to_TYPE to_type) {char * p = new char [str.size ()]; Memcpy (p, str.c_str (), str.size ()); Switch (to_type) {case TO_INT: {vector & lt; Int & gt; Race; Four * tokens; Four * state; (Token = Strottoca_r (p, cement and state); token! = Tap; token = strotok_r (tap, delay, and state)) {res.push_back (atoi (token)); } Delete [] P; Return ridge; }             break; Case TO_FLOAT: {Vector & lt; Float & gt; Race; Four * tokens; Four * state; (Token = Strottoca_r (p, cement and state); token! = Null; token = strotok_r (tap, delay, and state)) {res.push_back (atf (token)); } Delete [] P; Return ridge; }             break; Case TO_STRING: {Vector & lt; String & gt; Race; Four * tokens; Four * state; (Token = strotok_r (p, cement and state); token! = Tap; token = strotok_r (tap, delay, and state)) {res.push_back (string (token)); } Delete [] P; Return ridge; }             break; }}  

Usage:

  string str = "lab, yuv, hsv"; Of vector & lt; String & gt; Colorspace = string_to_token & lt; String & gt; (Str, ""); There are errors in the line  return res  in  

.

I have tried to use the void (* change_func) (char * temp_str) as a callback function, but I do not know how to implement it. If you were comfortable, could you give me some advice? Thanks a lot.

The reason for the error is that your template is compiled (example int ):

  template & lt; & Gt; Of vector & lt; Int & gt; String_to_token (string & str, const char * delim, TO_TYPE to_type) {// ... switch (to_type) {case TO_INT: {vector & lt; Int & gt; Race; // ... returns leak; // it's okay) break; Case TO_FLOAT: {Vector & lt; Float & gt; Race; // ... returns leak; // will try to return this vector & lt; Float & gt; For a vector & lt; Int & gt; }         break; Case TO_STRING: {Vector & lt; String & gt; Race; // ... returns leak; // will try to return this vector & lt; String & gt; For a vector & lt; Int & gt; }         break; }}  

You are trying to solve two problems with this function:

  • tokenization (see solution)

  • string conversion

Consider splitting this function into two halves:

  • First, a non-stenal :: string in the vector Token sample function

  • Second, a change (which can be easily toppled by type):

Code:

< Pre> std :: vector & lt; Std :: string & gt; String = tokenize (str, ","); // see std :: vector & lt; Int & gt; Ints {strings.size ()}; Std :: transforms (strings.begin (), strings.end (), ints.begin (), [] (const std :: string & amp; s) {return std :: stoi (s);});

Comments