is there in C# a method for List like resize in c++ for vector

后端 未结 7 1388
無奈伤痛
無奈伤痛 2021-01-03 18:14

When I use resize(int newsize) in C++ for vector, it means that the size of this vector are set to newsize

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 18:58

    This is my solution.

    private void listResize(List list, int size)
    {
       if (size > list.Count)
          while (size - list.Count > 0)
             list.Add(default);    
       else if (size < list.Count)
          while (list.Count - size > 0)
             list.RemoveAt(list.Count-1);
    }
    

    When the size and list.Count are the same, there is no need to resize the list.

    The default(T) parameter is used instead of null,"",0 or other nullable types, to fill an empty item in the list, because we don't know what type is (reference, value, struct etc.).

    P.S. I used for loops instead of while loops and i ran into a problem. Not always the size of the list was that i was asking for. It was smaller. Any thoughts why?

    Check it:

    private void listResize(List list, int size)
    {
       if (size > list.Count)
          for (int i = 0; i <= size - list.Count; i++)
             list.Add(default(T));
       else if (size < list.Count)
          for (int i = 0; i <= list.Count - size; i++)
             list.RemoveAt(list.Count-1);
    }
    

提交回复
热议问题