C
C#2y ago
wcasa

✅ inputting list..

var size = int.Parse(Console.ReadLine());

List<int> arr = new List<int>(size);
for (int i = 0; i < size; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
var size = int.Parse(Console.ReadLine());

List<int> arr = new List<int>(size);
for (int i = 0; i < size; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
whats wrong with this code
13 Replies
ero
ero2y ago
you tell us
wcasa
wcasaOP2y ago
nukleer bomb
nukleer bomb2y ago
List<T> length is zero when created
Jimmacle
Jimmacle2y ago
the capacity of a list is not the same as its size
nukleer bomb
nukleer bomb2y ago
That argument you are passing is capacity, not actual length
wcasa
wcasaOP2y ago
List<int> arr = new List<int>(size); doesnt it say "create list with this size" ohhhh forgot those exist so i need to pushback them 1 by 1? is there more efficient solution? sounds slow..
nukleer bomb
nukleer bomb2y ago
it's already efficient if you keep parameter in constructor
wcasa
wcasaOP2y ago
var size = int.Parse(Console.ReadLine());

List<int> arr = new List<int> { };
for (int i = 0; i < size; i++)
{

int val = int.Parse(Console.ReadLine());
arr.Add(val);
}
var size = int.Parse(Console.ReadLine());

List<int> arr = new List<int> { };
for (int i = 0; i < size; i++)
{

int val = int.Parse(Console.ReadLine());
arr.Add(val);
}
so thats the way?
nukleer bomb
nukleer bomb2y ago
It's efficient because List prepared some memory for size elements when constructor is called, but just didn't use it until Add is called
wcasa
wcasaOP2y ago
so i should have that (size) at the end of the list?
nukleer bomb
nukleer bomb2y ago
You can drop it, but it will be less efficient
wcasa
wcasaOP2y ago
okie thanks men! !close
Accord
Accord2y ago
Closed!
Want results from more Discord servers?
Add your server