jeudi 26 mai 2022

How is a vector

I am not efficient in C++ and I am looking to know what is the right way in modern C++ or efficient place to return a vector and use the result. Here is my program. How can I make this more efficient in terms of memory copying, etc?

#include <vector>

std::vector<int> get_space_pos(const std::string &s){
    std::vector<int> results;
    std::vector<char> v(s.begin(), s.end());
    for(int i=0; i< v.size(); i++)
    {
        if ( v[i] == ' ')
         {
             results.push_back(i);
         }
    }
    return results;
}

int main() {    
    const std::string s = "My name is great";
    const std::vector<int> res = get_space_pos(s); // Is this a bad practice?? do I need to do some move or something more efficient.
                                                   // are the results here going to copy as a reference to res or a deep copy?
    for( auto &elem : res)
    {
        std::cout<<elem<<std::endl;
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire