0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[tips][cpp] copy

Last updated at Posted at 2024-10-22

copy

  • 代入 配列1= 配列2
  • std::copy
  • move

の三つがあります。
vector<int>型などで、新しい配列を用意して、元の配列の値を変更したくない時には配列1= 配列2を使用するのが良さそうです。

代入動作は、コピー元の配列と同じストレージを持つ配列を用意し、そこに基本型を割り当てていく動作のようです。

vector<int> a = {1, 2, 3};
vector<int> b(3) = a;

実際の内部動作

b[0] = a[0] ;
b[1] = a[1] ;
b[2] = a[2] ;

この動作のため、コピー先配列bの要素を変更してもコピー元配列aには反映されません。

b[0] = 999;
cout << "a[0]:" << a[0] << endl;
cout << "b[0]:" << b[0] << endl;

output

a[0]:1
b[0]:999

※参考 https://ezoeryou.github.io/cpp-intro/#vector%E3%81%AE%E3%82%B3%E3%83%94%E3%83%BC

作成中
#include <iostream>
#include <vector>
using namespace std;

int main(){
    vector<int> a = {1, 2, 3};
    cout << &a[0] << endl;

    vector<int> b = a;
    cout << &b[0] << endl;

    // shallow copy
    vector<int> c(a.size());
    copy(a.begin(), a.end(), c.begin());
    cout << &c[0] << endl;
}

copy()関数によるコピーと=演算子によるコピー。

output

0x14a606bc0
0x14a606bd0
0x14a606be0

参考

cpp-book

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?