Best way to return list of objects in C++?

前端 未结 5 721
故里飘歌
故里飘歌 2021-02-12 08:48

It\'s been a while since I programmed in C++, and after coming from python, I feel soooo in a straight jacket, ok I\'m not gonna rant.

I have a couple of functions that

5条回答
  •  清酒与你
    2021-02-12 09:22

    I'd use the generic approach:

    template 
    void DoMagic(InIt first, InIt last, OutIt out)
    {
      for(; first != last; ++first) {
        if(IsCorrectIngredient(*first)) {
          *out = DoMoreMagic(*first);
          ++out;
        }
      }
    }
    

    Now you can call it

    std::vector ingredients;
    std::vector result;
    
    DoMagic(ingredients.begin(), ingredients.end(), std::back_inserter(results));
    

    You can easily change containers used without changing the algorithm used, also it is efficient there's no overhead in returning containers.

提交回复
热议问题