2

I was trying to rewrite some C++ code I found on the internet in C# for my hexagon sphere project, but I ran into the following code:

if((((*ti)->m_hexA) != tileNdx) && (find(nbrs. begin(), nbrs.end(), ((*ti)->m_hexA)) == nbrs.end()))
{
    nbrs.push_back(((*ti)->m_hexA));
}

I have it mostly converted to C#. I even built my own Find<T>(List<T> list, T value) method that achieves the same basic functionality as std::find.

I am still unsure about the docs for std::vector<T>::end() however. The docs say it returns an iterator pointing to a "place holder" slot at the end of the iterator, and that attempting to access it will result in "undefined behaviour". Does this:

1.) Mean that in my C#, when dealing with regular objects performing comparisons with an end() element, I should just compare the object to null?

2.) With integers and other primitives, should I just compare against a sentinel value such as -1?

In the above c++ source code, nbrs is a std::vector, m_hexA is an int, and ti is a struct.

Jax
  • 402
  • 7
  • 24
  • Don't use a custom find. Use linq's `Where`. `var relevantElements = myList.Where(o => conditionSatisfied(o));` – Millie Smith Jul 06 '17 at 04:00
  • 3
    C# is a different language than C++. It calls for different constructs and different idioms. `end` will not get directly translated over, in the same way that many sentences in German might not be directly translated into exactly the same sentences in English. – Millie Smith Jul 06 '17 at 04:02
  • 2
    That code is checking if the item exists in the list. In C#: `if (... && !nbrs.Contains(ti.m_hexA)) { nbrs.Add(ti.m_hexA); };` – Millie Smith Jul 06 '17 at 04:04
  • Can you please describe a case where regular show `IEnumerable` does not work for you? – Alexei Levenkov Jul 06 '17 at 04:04
  • @MillieSmith Thanks. I figured as much, but the `((ti)->m_hexA)) == nbrs.end()` was throwing me off. My thought process was something like "if nbrs.end() was empty they would just use NULL, as it wouldn't make sense to compare the previous value to it". – Jax Jul 06 '17 at 04:10

1 Answers1

1

The whole construction:

(find(nbrs. begin(), nbrs.end(), ((*ti)->m_hexA)) == nbrs.end())

could be written in C# using LinQ:

nbrs.FirstOrDefault(i => i == ti.m_hexA) == null

or

!nbrs.Any(i => i == ti.m_hexA)

where ((*ti)->m_hexA) is equivalent of ti.m_hexA.

Roman Ananyev
  • 519
  • 1
  • 5
  • 16