Как применить OrderBy в C++/CLI?

192
19 апреля 2018, 09:51

Доброе утро, всем!! Есть класс на C#:

class HuffmanTree
{
    private List<Node> nodes = new List<Node>();
    public Node Root { get; set; }
    public Dictionary<char, int> Frequencies = new Dictionary<char, int>();
    public void Build(string source)
    {
        for (int i = 0; i < source.Length; i++)
        {
            if (!Frequencies.ContainsKey(source[i]))
            {
                Frequencies.Add(source[i], 0);
            }
            Frequencies[source[i]]++;
        }
        foreach (KeyValuePair<char, int> symbol in Frequencies)
        {
            nodes.Add(new Node() { Symbol = symbol.Key, Frequency = symbol.Value });
        }
        while (nodes.Count > 1)
        {
            List<Node> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList<Node>();
            if (orderedNodes.Count >= 2)
            {
                // Take first two items
                List<Node> taken = orderedNodes.Take(2).ToList<Node>();
                // Create a parent node by combining the frequencies
                Node parent = new Node()
                {
                    Symbol = '*',
                    Frequency = taken[0].Frequency + taken[1].Frequency,
                    Left = taken[0],
                    Right = taken[1]
                };
                nodes.Remove(taken[0]);
                nodes.Remove(taken[1]);
                nodes.Add(parent);
            }
            this.Root = nodes.FirstOrDefault();
        }
    }
    public BitArray Encode(string source)
    {
        List<bool> encodedSource = new List<bool>();
        for (int i = 0; i < source.Length; i++)
        {
            List<bool> encodedSymbol = this.Root.Traverse(source[i], new List<bool>());
            encodedSource.AddRange(encodedSymbol);
        }
        BitArray bits = new BitArray(encodedSource.ToArray());
        return bits;
    }
    public string Decode(BitArray bits)
    {
        Node current = this.Root;
        string decoded = "";
        foreach (bool bit in bits)
        {
            if (bit)
            {
                if (current.Right != null)
                {
                    current = current.Right;
                }
            }
            else
            {
                if (current.Left != null)
                {
                    current = current.Left;
                }
            }
            if (IsLeaf(current))
            {
                decoded += current.Symbol;
                current = this.Root;
            }
        }
        return decoded;
    }
    public bool IsLeaf(Node node)
    {
        return (node.Left == null && node.Right == null);
    }
}

Я перевёл на C++/CLI и ошибка в OrderBy:

using namespace System;

private ref class HuffmanTree
{
    private:
        List<Node^> ^nodes = gcnew List<Node^>();
    public:
        property Node ^Root;
        Dictionary<Char, int> ^Frequencies = gcnew Dictionary<Char, int>();
        void Build(String ^source)
        {
            for (int i = 0; i < source->Length; i++)
            {
                if (!Frequencies->ContainsKey(source[i]))
                {
                    Frequencies->Add(source[i], 0);
                }
                Frequencies[source[i]]++;
            }
            for each (KeyValuePair<Char, int> ^symbol in Frequencies)
            {
                Node ^tempVar = gcnew Node();
                tempVar->Symbol = symbol.Key;
                tempVar->Frequency = symbol.Value;
                nodes->Add(tempVar);
            }
            while (nodes->Count > 1)
            {
                List<Node^> ^orderedNodes = nodes->OrderBy(AnonymousMethod1)->ToList<Node^>();
                if (orderedNodes->Count >= 2)
                {
                    // Take first two items
                    List<Node^> ^taken = orderedNodes->Take(2)->ToList<Node^>();
                    // Create a parent node by combining the frequencies
                    Node ^parent = gcnew Node();
                    parent->Symbol = '*';
                    parent->Frequency = taken[0]->Frequency + taken[1]->Frequency;
                    parent->Left = taken[0];
                    parent->Right = taken[1];
                    nodes->Remove(taken[0]);
                    nodes->Remove(taken[1]);
                    nodes->Add(parent);
                }
                this->Root = nodes->FirstOrDefault();
            }
        }
    private:
        void AnonymousMethod1(Object ^node)
        {
            node->Frequency;
        }
    public:
        BitArray ^Encode(String ^source)
        {
            List<bool> ^encodedSource = gcnew List<bool>();
            for (int i = 0; i < source->Length; i++)
            {
                List<bool> ^encodedSymbol = this->Root->Traverse(source[i], gcnew List<bool>());
                encodedSource->AddRange(encodedSymbol);
            }
            BitArray ^bits = gcnew BitArray(encodedSource->ToArray());
            return bits;
        }
        String ^Decode(BitArray ^bits)
        {
            Node ^current = this->Root;
            String ^decoded = "";
            for each (bool bit in bits)
            {
                if (bit)
                {
                    if (current->Right != nullptr)
                    {
                        current = current->Right;
                    }
                }
                else
                {
                    if (current->Left != nullptr)
                    {
                        current = current->Left;
                    }
                }
                if (IsLeaf(current))
                {
                    decoded += current->Symbol;
                    current = this->Root;
                }
            }
            return decoded;
        }
        bool IsLeaf(Node ^node)
        {
            return (node->Left == nullptr && node->Right == nullptr);
        };
}

Помогите пожалуйста, исправить правильно...

Answer 1

OrderBy — это метод расширения, который лежит в классе Enumerable, соответственно вместо source.OrderBy(...) всегда можно написать Enumerable.OrderBy(source, ...). Переведите это на C++ и всё заработает.

Это же относится и к прочим методам расширения, таким как ToList, Take, FirstOrDefault, ToArray (это из того что я увидел в вашем фрагменте).

READ ALSO
C# передача больших файлов(больше 8 кб) по UDP

C# передача больших файлов(больше 8 кб) по UDP

Доброе утро, всем!! Есть клиент-серверное приложение на C#Сервер:

162
Как сравнить даты

Как сравнить даты

Есть заранее известная датаНапример, есть некий документ от 01

187
Взаимодействие с двумя окнами MVVM C#

Взаимодействие с двумя окнами MVVM C#

Пробую освоить MVVM, дается очень тяжелоВ теории вроде понятно, а вот как на практике реализовать, не очень понимаю

175
Изменить под регулярные выражения

Изменить под регулярные выражения

Как заменить кучу Replace на регулярные выражения ?

164