C ++:复制一部分双打的最快方法

时间:2013-06-14 17:14:32

标签: c++ optimization

目前我有以下代码将一些双打复制到另一个双打矢量。

for (int i = 0;i<=iTo;i++)
{

    int iID= i + iOff;
    double d=m[iID];
    uTargets[iSamplePos]=d;
    iSamplePos++;
}

如果没有“手动”迭代,有人能告诉我最快的方法吗?

谢谢!

3 个答案:

答案 0 :(得分:4)

如果您要覆盖现有的矢量:

uTargets.assign(m.begin() + iOff, m.begin() + iOff + iTo + 1);

如果您要复制到已存在的范围:

std::copy(m.begin() + iOff, m.begin() + iOff + iTo + 1, uTargets.begin() + iSamplePos);

答案 1 :(得分:1)

你可以使用memcpy(uTargets,m + iOFF,(iTo-iOff + 1)* sizeof(double)); 但我会坚持使用更可靠的方法,如迭代或std :: copy,除非你需要复制大量的内存。

答案 2 :(得分:1)

请查看C ++标准库的algorithm部分的文档。

  

算法库定义了各种用途的函数   (例如,搜索,排序,计数,操纵)操作   元素范围。请注意,范围定义为[first,last)   where last指的是要检查的最后一个元素的元素   修改

通常,对于以不同方式遍历容器并对其元素应用某种转换等操作,您应该依赖标准接口。

在你的特定情况下,你提到你有两个向量(我假设你的意思是你的类std::vector<T>的对象)。

正如其他人所提到的,您可以使用算法std::copy,它采用以下语法:

std::copy(source.begin(), source.end(), destination.begin())

现在,你必须要小心。这假设destination已经保留了空间。也就是说,在该行之前的某个位置创建目标为:

std::vector<double> destination(source.size());

如果不是这种情况,你可以使用一种叫做&#34;后插入器的迭代器&#34;。

以下示例可以解释一下(注意std::iota只是用一个序列填充一个容器(例如,k,k ++,k ++,...))

#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>

void show(const char* name, std::vector<double>& v) {
  std::cout<<"Vector '"<<name<<"'"<<std::endl;
  for(auto & item : v) {
    std::cout<<item<<" ";
  }
  std::cout<<std::endl;
}

int main() {
  // create a vector to store twenty doubles
  std::vector<double> source(20);
  // fill with the numbers 0, 1, ..., 19
  std::iota(source.begin(), source.end(), 0);

  // let's peek 
  show("Source", source);

  // create a destination vector capable of holding the values
  std::vector<double> destination_1(source.size());
  // copy the values
  std::copy(source.begin(), source.end(), destination_1.begin());

  show("Destination 1", destination_1);

  // create a destination vector without space reserved
  std::vector<double> destination_2;
  // copy the values (use the back inserter)
  std::copy(source.begin(), source.end(), std::back_inserter(destination_2));

  show("Destination 2", destination_2);

  return 0;
}

输出(使用C ++ 11支持使用g ++ 4.7.2编译,即c++ file.cpp -std=c++11):

Vector 'Source'
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
Vector 'Destination 1'
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
Vector 'Destination 2'
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19