C++14 using auto keyword in a method's definition

后端 未结 3 973
不思量自难忘°
不思量自难忘° 2021-02-19 18:46

I have several std::unordered_maps. They all have an std::string as their key and their data differs. I want to make a csv string from a given map\'s k

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 19:12

    As in C++14 auto parameters are only allowed in lambdas (as per @ildjarn's comment), you can just develop a function template, templateized on the map type, e.g.:

    #include 
    #include 
    #include 
    
    class myClass {
    ...
    
    template 
    std::string getCollection(const MapType& myMap) {
        std::vector  tmpVec;
        for ( const auto& elem : myMap) {
            tmpVec.push_back(elem.first);
        }
        std::stringstream ss;
        for ( const auto& elem : tmpVec ) {
            ss << elem <<',';
        }
        std::string result=ss.str();
        result.pop_back(); //remove the last ','
        return result;
    }
    

    Note also the addition of const for some const-correctness.

    Moreover, why not just building the output string directly using the string stream object, without populating an intermediate vector (which is more code, more potential for bugs, more overhead, less efficiency)?

    And, since you are just interested in using the string stream as an output stream, using ostringstream instead of stringstream is better as it's more efficient and communicates your intent better.

    #include   // for std::ostringstream
    #include    // for std::string
    ...
    
    template 
    std::string getCollection(const MapType& myMap) {
        std::ostringstream ss;
        for (const auto& elem : myMap) {
            ss << elem.first << ',';
        }
        std::string result = ss.str();
        result.pop_back(); // remove the last ','
        return result;
    }
    

提交回复
热议问题