欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

std::vector 如何对数组进行assign 和 push_back操作。

程序员文章站 2022-02-05 19:28:05
...

1) assign

  char arr[] = { 1,2,3 };
  std::vector<char> buffer;
  buffer.clear();
  buffer.insert(buffer.begin(), std::begin(arr), std::end(arr));
  assert(buffer.size() == 3);
  assert(buffer[0] == 1);
  assert(buffer[1] == 2);
  assert(buffer[2] == 3);

    或者

  char arr[] = { 101, 1,2,3 };
  std::vector<char> buffer(100, 100);
  buffer.assign(std::begin(arr), std::end(arr));
  assert(buffer.size() == 4);
  assert(buffer[0] == 101);
  assert(buffer[1] == 1);
  assert(buffer[2] == 2);
  assert(buffer[3] == 3);
或者
  char arr[] = { 101, 1,2,3 };
  std::vector<char> buffer(arr, arr + sizeof(arr)/sizeof(arr[0]));
  assert(buffer.size() == 4);
  assert(buffer[0] == 101);
  assert(buffer[1] == 1);
  assert(buffer[2] == 2);
  assert(buffer[3] == 3);

    如果只赋值数组的一部分:

  char arr[] = { 101, 1,2,3 };
  std::vector<char> buffer(arr, arr + 2);
 
  assert(buffer.size() == 2);
  assert(buffer[0] == 101);
  assert(buffer[1] == 1);

    或者

  char arr[] = { 101, 1,2,3 };
  std::vector<char> buffer(std::begin(arr), std::begin(arr) + 2);
 
  assert(buffer.size() == 2);
  assert(buffer[0] == 101);
  assert(buffer[1] == 1);

2) push_back

  char arr[] = { 1,2,3 };
  std::vector<char> buffer(1, 100);
  buffer.insert(buffer.cend(), std::cbegin(arr), std::cend(arr));
  assert(buffer.size() == 4);
  assert(buffer[0] == 100);
  assert(buffer[1] == 1);
  assert(buffer[2] == 2);
  assert(buffer[3] == 3);

    如果只赋值数组的一部分:

  char arr[] = { 1,2,3 };
  std::vector<char> buffer(1, 100);
  buffer.insert(buffer.cend(), std::cbegin(arr), std::cbegin(arr) + 1);
  assert(buffer.size() == 2);
  assert(buffer[0] == 100);
  assert(buffer[1] == 1);