What is the most efficient way to convert a std::vector to a .NET List?

前端 未结 3 1134
情歌与酒
情歌与酒 2021-02-14 01:38

What is the most efficient way to convert a std::vector to a .NET List?

To give some context, I am wrapping an unmanaged C++ class with C++/CLI. The C++/CLI class holds

相关标签:
3条回答
  • 2021-02-14 02:20

    If you're really that concerned about it, use unverifiable code instead:

    List<unsigned>^ MethodA()
    {
        std::vector<unsigned> const& runList = mpChannelNode->runList();
        array<unsigned>^ ret = gcnew array<unsigned>(runList.size());
        if (runList.size())
        {
            pin_ptr<unsigned> dest = &ret[0];
            std::memcpy(dest, &runList[0], runList.size() * sizeof(unsigned));
        }
        return gcnew List<unsigned>(ret);
    }
    

    That said, I'd be surprised if there was a noticeable difference either way...

    0 讨论(0)
  • 2021-02-14 02:21

    I am not familiar with C++-CLI but one small improvement you can make is to create your list with the right capacity from the beginning.

    List<UInt32> list = gcnew List<UInt32>(runList.size());
    

    Another improvement would be to pre-increment your C++ iterator instead of post-incrementing it because currently you create an extra object for every element that is discarded immediately.

    0 讨论(0)
  • 2021-02-14 02:22

    Consider turning into the vector directly into an array .. the below will work and be valid, until you resize the vector.

    vector vec(10); int *array = &vec[0];

    Then, you should be able to treat that (I think -- VS not on machine) as a passed array to populate your list.

    You should also create your list with a size that you expect to need -- adding one by one will be slow.

    0 讨论(0)
提交回复
热议问题