微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 如何将一个矢量块复制到另一个矢量块

我使用数组来存储数据,但是我用vector替换了,所以我想用c运算符替换所有的c运算符.我使用memcpy复制一个内存块
for (i = 0; i < rows_; i++)
    memcpy((T *) &tmp.data_[cols_ * i],(T *) &a.data_[cols_ * (2 * i + 1)],rows_ * sizeof(T));

它也在使用向量,我只想知道c中是否存在等效函数

我试过这个副本:

std::copy(tmp.data_[cols_ * i],tmp.data_[cols_ * i+rows],a.data_[cols_ * (2 * i + 1)]);

但我收到以下错误

error: invalid use of member function (did you forget the ‘()’ ?)

例如:

我有一个2xnxn大小的数组,我正在使用for循环来制作一个nxn数组.例如我有1 2 3 4 5 6 7 8,我的新阵列必须如下:3 4 7 8.我用memcpy来实现这一目标,但我不知道如何在c中实现

解决方法

如果从数组复制到向量,请使用 std::copystd::vector::assign
int from_array[10] = {1,2,3,4,5,6,7,8,9,10};

  std::vector<int> to_vector;

  int array_len = sizeof(from_array)/sizeof(int);
  to_vector.reserve(array_len);
  std::copy( from_array,from_array+10,std::back_inserter(to_vector)); 
  or C++11
  std::copy( std::begin(from_array),std::end(from_array),std::back_inserter(to_vector));   

  std::vector<int> to_vector2;
  to_vector2.reserve(array_len);
  to_vector2.assign(from_array,from_array + array_len);

如果从矢量复制到矢量

std::vector<int> v1;
   std::vector<int> v2;
   v2 = v1; // assign operator = should work

如果你不需要保留v1,std :: swap也可以

v2.swap(v1);

更新:

const int M = 2;
  const int N = 4;
  int from_array[M][N] = {{1,4},{5,8}};

  std::vector<int> to_vector;
  to_vector.reserve(N);
  int start=2;
  int end = 4;
  for (int i=0; i<M; i++)
  {
    std::copy( from_array[i]+start,from_array[i]+end,std::back_inserter(to_vector)); 
  }

原文地址:https://www.jb51.cc/c/111115.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐