Home  >  Article  >  Backend Development  >  How to copy a C++ STL container?

How to copy a C++ STL container?

王林
王林Original
2024-06-05 11:51:57804browse

There are three ways to copy a C++ STL container: Use the copy constructor to copy the contents of the container to a new container. Use the assignment operator to copy the contents of a container to the target container. Use the std::copy algorithm to copy the elements in the container.

如何复制C++ STL容器?

How to copy a C++ STL container

Preface

C++ Standard Template Library ( STL) provides a series of container classes for storing and managing data. Copying these containers is often necessary, for example, when we need to add elements to another container, or when we need to preserve the contents of the container before passing arguments to a function.

Use the copy constructor

The STL container provides a copy constructor, which copies the contents of the container to a new container. The syntax of the copy constructor is as follows:

std::vector<int> v1{1, 2, 3};
std::vector<int> v2(v1); // 复制 v1 到 v2

Using the assignment operator

The assignment operator (=) can also be used to copy the container. The assignment operator copies the contents of the source container to the target container, discarding any existing elements in the target container. The syntax of the assignment operator is as follows:

std::vector<int> v1{1, 2, 3};
std::vector<int> v2;
v2 = v1; // 复制 v1 到 v2

Using std::copy

std::copy algorithm can be used to copy elements in a container. The syntax of std::copy is as follows:

std::vector<int> v1{1, 2, 3};
std::vector<int> v2(v1.size());
std::copy(v1.begin(), v1.end(), v2.begin()); // 复制 v1 到 v2

Practical case

Suppose we have a vector container containing student information:

struct Student {
  int id;
  std::string name;
};

std::vector<Student> students = {
  {1, "Alice"},
  {2, "Bob"},
  {3, "Charlie"},
};

To copy this container, we can use the copy constructor:

std::vector<Student> students_copy(students);

or use the assignment operator:

std::vector<Student> students_copy;
students_copy = students;

Now, students_copy will contain the same student information as students.

The above is the detailed content of How to copy a C++ STL container?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn