【问题标题】:How to efficiently move an array to a vector in C++? [duplicate]如何有效地将数组移动到 C++ 中的向量? [复制]
【发布时间】:2019-01-10 12:34:46
【问题描述】:

我正在使用一个函数,该函数需要我传入一个 C 样式的数组,以便可以用数据填充它。但是,生成的数组必须转换为向量,以便可以将其传递给另一个需要它的函数。矢量约束很难,无法绕过它。可以想象,我可以重新设计另一个函数,以便它接受一个向量,但如果它可以有效地完成,我不希望这样做。具体来说,如果可能的话,我希望不要将数据从数组复制到向量。作为一个最小的例子,采取以下程序:

#include <iostream>
#include <algorithm>
#include <vector>
#include <chrono>

using namespace std::chrono;

static uint LENGTH = 10000000;


uint now() {
    return duration_cast<microseconds>
            (system_clock::now().time_since_epoch()).count();
}

void put_data_in_array(char *data) {
    std::cout << now() << " filling array\n";
    for (uint i = 0; i < LENGTH; i++) {
        data[i] = i;
    }
    std::cout << now() << " filled array\n";
}

int main () {
    std::cout << now() << " making array\n";
    char *array = new char[LENGTH];
    std::cout << now() << " made array\n";
    put_data_in_array(array);
    std::cout << now() << " function returned\n";
    std::vector<char> v;
    std::move(array, array + LENGTH, std::back_inserter(v));
    std::cout << now() << " switched to vector\n";
  return 0;
}

产生以下输出:

1970760826 making array
1970760926 made array
1970760927 filling array
1970774417 filled array
1970774421 function returned
1970879936 switched to vector

意思:

100 µs to allocate memory for the array
13490 µs to fill the array
105515 µs to move the array to a vector

理想情况下,我希望将数组移动到向量的时间非常小。如果可能的话,我想告诉向量获取现有数组的所有权。但是,如果将其传输到向量的时间可以接近(少于两倍)填充数组所需的时间,我会很高兴。

感谢您提供的任何帮助。

编辑:

感谢所有快速反馈!事实证明,通过v.data() 可能是完成我正在寻找的最佳方式。我真的一点也不关心array,我只知道我必须将一个数组传递给函数。

【问题讨论】:

  • 你需要reservev中的空格。
  • @NathanOliver 我什至没有想过它必须增长多少次。谢谢!
  • 我真的需要多出去走走。显然std::move 侏儒一直很忙。该死的 RL 再次干扰我的标准浏览时间
  • 另外,从一开始就考虑使用vector。您可以将其.data() 传递给put_data_in_array
  • @WhozCraig 抱歉,我不在了。什么是“std::move gnome”?还有,“RL”?

标签: c++ performance c++11 vector


【解决方案1】:

没有办法避免将数组复制到向量中。

最有效的方式应该是使用向量构造函数进行复制。使用两个指针,它们的作用类似于开始/结束迭代器。

std::vector<int64_t> v(array, array + LENGTH);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 2017-10-18
    • 2019-11-11
    • 1970-01-01
    • 2015-08-13
    • 2020-09-04
    • 2023-03-30
    相关资源
    最近更新 更多