I am writing a utility function which can be a vector of elements (string, int, double, four) and one It looks like adding it to a single string and return it:
template & lt; Typename T & gt; Std :: string convert2Str (std :: vector & lt; T & gt; Conte & Week) {std :: ostringstream sStream; For (size_tk = 0; k & lt; vec.size (); ++ k) {Sstream & lt; & Lt; Vec [k] & lt; & Lt; ""; } Return sStream.str (); } I would like to make this function more common:
-
vector & lt; T & gt; . I have tried std :: vector & lt; T & gt; :: const_iterator this = vec.begin () before the loop and the compiler gave me an error: error: expected ; Before I was std :: vector & lt; Std :: string> gt; Const_iterator it = vec.begin () changes the above defintions to remove the error. Therefore, it seems that I am not following the correct syntax, please let me know what it is - Second, the first argument is to make the function more normal by making the container independent, looking at any container (
vector , list , queue , deque , etc.) I have to do the same thing as above. I tried to find it in the stack overflow and did not receive a satisfactory answer.
Step 1, as you said, use the iterator:
template & lt; Typename T & gt; Std :: string convert2Str (std :: vector & lt; T & gt; Conte & Week) {typedef std :: vector & lt; T & gt; Container; Std :: ostringstream sStream; (Typem Container :: Constructor for this = V. BGIN (); it! = Vec.end (); ++ this) {SSTREME & lt; & Lt; * This is & lt; & Lt; ""; } Return sStream.str (); } Step 2, type the template logic instead of the element type (you type the element type with value_type : Can get template & gt; typename container & gt; std :: string convert2Str (container const & vec) {typedef container :: value_type T; // if necessary std :: ostringstream sStream ; For (typename container :: const_iterator it = vec start (), it! = Vec.end (); ++ this) {sStream In C ++ 0x, it becomes even simpler (and typename is not required): Template & typ; typewriter container & gt; std :: string convert2Str (container const & amp;; Vec) using {std :: end; std :: end; std :: ostringstream for sStream; (auto = Start (vec); it! = End (vec); ++ it) {typedef decltype (* it);; // If necessary, sstream & lt; & lt; * this & lt; & lt; ""; } Return sStream.str ();} In other advantages, std:: start working for raw AR and std :: end AIS
Comments
Post a Comment