An artist's depiction of an Extended Unit Death
C++ doesn't have garbage collection because the idea is that it's too important to leave to a compiler for people to ignore. So it's not "crap" at collections, C++ and C# have just vastly different design intentions.
I meant as far as actually using collections, it seems to be a lot more work in C++ than C# in most scenarios. For example, say I have a Person object with a Cash property (decimal) and a Country property (enum). I have a collection of People, and I want to get all U.S. citizens with at least 50.0 cash and give them $5 more. Here's the entities in C#:
public class Person
{
public decimal Cash { get; set; }
public CountryEnum Country { get; set; }
}
public enum CountryEnum
{
US,
CA
}
As for the actual code:
IEnumerable<Person> people = GetPeople(); //however the list is obtained, unimportant for this example
people = people.Where(person => person.Country == CountryEnum.US && person.Cash > 50);
foreach(Person person in people)
{
person.Cash += 5;
}
Or, if you prefer to be more succinct, you can do it all like this:
GetPeople().Where(x => x.Country == CountryEnum.US && x.Cash > 50).ForEach(x => x.Cash += 5);
Granted, I only know a little C++, but I can't imagine it being more succinct than that. You would need to declare your iterator, specify the begin and end of the for loop, etc., etc. If you needed to use that filtered list again (like, say I wanted to print to the console the sum of those people's cash), in C# you'd already have the variable ready in the first implementation, but in C++ you'd have to either filter it again (dumb idea) or declare a new list variable and add each desired person in the for loop to that new variable. C++ would be more optimized in this example because you'd only iterate over the collection once, though I could easily rewrite the C# code to do the same:
var people = GetPeople();
var peopleSubset = new List<Person>();
foreach(var person in People)
{
if(person.Country == CountryEnum.US && person.Cash > 50)
{
person.Cash = person.Cash + 5;
peopleSubset.Add(person);
}
}
Console.WriteLine(peopleSubset.Select(x => x.Cash).Sum());
All-in-all, I find working with collections in C# to be much more flexible than C++. I go by "the best code is no code at all," though, so that's why I prefer succinctness (less room for error). That's why I said C++ is crap at collections by comparison.
Post has been edited 1 time(s), last time on Jul 9 2012, 2:13 am by Roy.