Removing alternate elements in a List

后端 未结 8 1096
执笔经年
执笔经年 2021-02-12 18:41

What is the most efficient way to remove alternate (odd indexed or even indexed) elements in an List without using a place holder list variable?

A

相关标签:
8条回答
  • 2021-02-12 18:57

    The way to Nirvana is paved with deferred execution. Or something.

        public static IEnumerable<T> AlternateItems<T>(this IEnumerable<T> source)
        {
            while (source.Any())
            {
                yield return source.First();
    
                source = source.Skip(1);
    
                if (source.Any()) source = source.Skip(1);                
            }
        }
    

    This works for all sequences, not just IList<>. The cost of iteration is deferred until iteration, which may be a big win if, in the end, you don't need to touch all the elements in the list.

    In my simple tests, the performance when you iterate over the whole list is not very good, so be sure to profile your real situation.

    0 讨论(0)
  • 2021-02-12 19:02

    I would use the standard pattern generally used for STL containers. Do a remove followed by an erase.

    This way you will not confuse people that are used to seeing this pattern.

    template<typename T>
    struct RemoveEven
    {
        RemoveEven():count(0)   {}
        bool operator()(T const&)
        {
            bool    result  =  count%2 == 0;
            count++;
            return result;
        }
        private:
            std::size_t count;
    };
    int main()
    {
        std::list<int>  a;
        a.erase(std::remove_if(a.begin(),a.end(),RemoveEven<int>()),a.end());
    
    }
    
    0 讨论(0)
提交回复
热议问题