Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy one vector block to the other

Tags:

c++

memory

I used array to store the data, but I replaced with vector, so I would like to replace all the c operators with c++ operators. I used memcpy to copy one memory blocks

for (i = 0; i < rows_; i++)
    memcpy((T *) &tmp.data_[cols_ * i], (T *) &a.data_[cols_ * (2 * i + 1)], rows_ * sizeof(T));

It's also working with vectors, I just want to know is there an equivalent function in c++?

I tried the copy:

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

but I'm receiving the following error:

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

For example:

I have an 2xnxn size array and I'm using the for cycle to make an nxn array instead. for example I have 1 2 3 4 5 6 7 8, my new array has to be the following: 3 4 7 8. I used memcpy to achieve this, but I don't know how can I achieve in c++

like image 757
OHLÁLÁ Avatar asked Nov 26 '12 07:11

OHLÁLÁ


2 Answers

There is a standard algorithm copy. It is safer than memcpy because it works also for non-POD types. It is sometimes optimized for POD types to result in memcpy. You usually don't use pointers with standard algorithms, but you have to use iterators. To get an iterator you use begin() and end() methods or free functions. Example:

vector<int> a(10, 5);
vector<int> b(5);

copy(a.begin(), a.begin()+5, b.begin());
like image 53
Juraj Blaho Avatar answered Sep 20 '22 12:09

Juraj Blaho


Use std::copy or std::vector::assign if you copy from array to vector

  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);

if copy from vector to vector

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

if you don't need to keep v1, std::swap also works

v2.swap(v1);

Update:

  const int M = 2;
  const int N = 4;
  int from_array[M][N] = {{1,2,3,4},{5,6,7,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)); 
  }
like image 26
billz Avatar answered Sep 20 '22 12:09

billz