views:

1528

answers:

4

Can someone point out a good mapping between the usual C++ STL containers such as vector, list, map, set, multimap... and the C# generic containers?

I'm used to the former ones and somehow I've accustomed myself to express algorithms in terms of those containers. I'm having some hard time finding the C# equivalent to those.

Thank you!

A: 

There isn't a terrific direct mapping, since e.g. C++ set and map use comparators, whereas .Net HashSet and Dictionary use hash codes.

Brian
A: 

This SorceForge project looks like an interesting resource for what your looking for.

JP Alioto
+5  A: 

Here's a rough equivalence:

  1. Dictionary<K,V> <=> hash_map<K,V>
  2. HashSet<T> <=> hash_set<T>
  3. List<T> <=> vector<T>
  4. LinkedList<T> <=> list<T>

The .NET BCL (base class library) does not have red-black trees (stl map) or priority queues (make_heap(), push_heap(), pop_heap()).

.NET collections don't use "iterators" the way C++ does. They all implement IEnumerable<T>, and can be iterated over using the "foreach statement". If you want to manually control iteration you can call "GetEnumerator()" on the collection which will return an IEnumerator<T> objet. IEnumerator<T>.MoveNext() is roughly equivalent to "++" on a C++ iterator, and "Current" is roughly equivalent to the pointer-deference operator ("*").

C# does have a language feature called "iterators". They are not the same as "iterator objects" in the STL, however. Instead, they are a language feature that allows for automatic implementation of IEnumerable<T>. See documentation for the yield return and yield break statements for more information.

Scott Wisniewski
Sorry, but I think you have C++ and Java slightly confused there. (Though the rest of your discussion seems right, all the classes you list on the right of the table are Java collections, not STL containers.)
crosstalk
I had the casing wrong, and I left out "_" in the hash stuff (they are non standard, but most compilers support them).I updated the names.
Scott Wisniewski
+1  A: 

You may also want to take a look at STL/CLR which is

... is a packaging of the Standard Template Library (STL), a subset of the Standard C++ Library, for use with C++ and the .NET Framework common language runtime (CLR). With STL/CLR, you can use all the containers, iterators, and algorithms of STL in a managed environment.

Also, keep in mind that you can compile your existing C++/STL code with the /clr flag.

Dan
Do you have any experience with that? As I understand it, it only allows you to use STL-like code in managed C++. It doesn't provide a language-agnostic STL-alike implementation, does it? I'd love to have something like STL in C#. :)
jalf
I haven't actually tried this, but it looks like "all" you'd have to do is add a reference to Microsoft.VisualC.STLCLR and implement IVector<> (or IDeque<>, IList<>, etc.)
Dan