0

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;
}
user438383
  • 5,716
  • 8
  • 28
  • 43
  • 7
    Why are you making a copy of `s` into `v`? You can use `operator[]` on `s`. – NathanOliver May 26 '22 at 12:53
  • 6
    What you did just now, just simply returning a `std::vector` by value is usually the best approach, there should be no deep copy thanks to copy elision. https://en.cppreference.com/w/cpp/language/copy_elision – Kaldrr May 26 '22 at 12:54
  • 3
    @Kaldrr Since `results` is a named object, it only qualifies for NRVO, which may or may not happen. It will get moved though if NRVO does not apply. – NathanOliver May 26 '22 at 12:55
  • It's not bad practice. You do not need to do anything to make it more efficient. The results will either use a *named return value optimization* or an efficient *move*. – Eljay May 26 '22 at 13:03
  • @OP -- Also, unless it is obvious that the code will be slow (maybe an inefficient algorithm or data structure is used), you won't be able to pin down whether the code is optimal or not. See the [as-if](https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule) rule -- by the time the compiler optimizes the code, the code may look nothing like your original program. When you write a C++ program, you are only describing what the program should do -- as long as the compiler follows this description, that's all that matters. – PaulMcKenzie May 26 '22 at 13:08
  • Most modern C++ compilers implement NRVO, the code looks fine. Just might want to [`reserve`](https://en.cppreference.com/w/cpp/container/vector/reserve) some space in the `results` vector, if you know approximately how many elements you expect to insert. E.g. `results.reserve(s.size() / 4);` – rustyx May 26 '22 at 13:12

0 Answers0