C++ 向量对

C++ 向量对

C++中的向量是什么

C++中,向量是一种序列容器,将相同类型的元素存储在连续的内存块中 。向量中的每个元素都被分配一个数字索引,用于访问该元素。向量类似于数组,但其优点是能够动态增长和缩小大小。这意味着我们可以在向量中添加和删除元素,而不需要提前指定向量的大小。

C++中的向量对是什么

向量对是一对用于存储相关数据的向量 。例如,您可以使用向量对在二维空间中存储点的x和y坐标。对中的第一个向量将包含x坐标,第二个向量将包含相应的y坐标。

要在C++中使用向量对,我们必须在代码中包括<vector><utility>头文件。<vector>头文件提供了std::vector类,用于创建向量,而<utility>头文件提供了std::pair类,用于创建向量对。

C++中的向量对语法

pair<std::vector<data_type>, std::vector<data_type>> Variable;

示例1: 这是一个简单程序的示例,演示了如何在C++中使用向量:

#include 
#include 
using namespace std;

int main() {
  // Create a vector of integers
  vector v = {10, 20, 30, 40, 50};

  // Print the elements of the vector
  for (int i = 0; i < v.size(); i++) {
    cout << v[i] << " ";
  }
  cout << std::endl;

  // Add a new element to the vector
  v.push_back(60);

  // Print the elements of the vector again
  for (int i = 0; i < v.size(); i++) {
    cout << v[i] << " ";
  }
  cout << std::endl;

  return 0;
}

输出:

C++ 向量对

解释:

以上代码用于展示C++中的向量。在这段代码中,我们创建了一个整数向量并添加了一些初始值。然后我们打印了向量的元素,向向量添加了一个新的元素,并再次打印了向量的元素,以显示向量的大小已经增加。

示例2:

以下是如何在C++中使用向量对的示例:

#include 
#include 
using namespace std;

int main() {
  // Create a vector pair
  spai, std::vector> vp;

  // Add some x and y coordinates to the vector pair
  vp.first.push_back(10);
  vp.first.push_back(20);
  vp.first.push_back(30);
  vp.second.push_back(15);
  vp.second.push_back(25);
  vp.second.push_back(35);

  // Print the x and y coordinates
  for (int i = 0; i < vp.first.size(); i++) {
    cout << "(" << vp.first[i] << ", " << vp.second[i] << ")" << std::endl;
  }

  return 0;
}

输出:

C++ 向量对

解释:

上述代码是用来演示C++中的向量对(vector pair)。在这个代码中,我们创建了一个向量对并添加了x和y坐标。然后将坐标打印到控制台上。请注意,x和y坐标存储在不同的向量中,可以使用向量对的first和second成员来访问它们。一旦我们创建了向量对,我们可以使用从std::vector类继承的push_back()方法向向量对中的单个向量添加元素。在这个示例中,我们向向量对中的第一个向量添加了三个x坐标,并向向量对中的第二个向量添加了三个y坐标。

向量对在C++中用于存储和操作相关的数据非常有用。它们可以在许多应用程序中使用,从简单的几何问题到更复杂的数据结构和算法。

示例-3

#include 
#include 
#include 
#include 

int main() {
  // Create a vector pair to store the names and ages of a group of people
  std::pair, std::vector> vp;

  // Add some names and ages to the vector pair
  vp.first.push_back("virat");
  vp.first.push_back("rohit");
  vp.first.push_back("rahul");
  vp.second.push_back(34);
  vp.second.push_back(35);
  vp.second.push_back(30);

  // Print the names and ages of the people
  for (int i = 0; i < vp.first.size(); i++) {
    std::cout << vp.first[i] << " is " << vp.second[i] << " years old." << std::endl;
  }

  return 0;
}

输出:

C++ 向量对

说明:

以上代码是用来演示在c++中使用vector pair。在这段代码中,我们创建了一个vector pair来存储一组人的姓名和年龄。我们向vector pair中添加姓名和年龄,并打印它们。一旦我们创建了vector pair,我们可以使用push_back()方法向pair中的每个vector添加元素,该方法继承自std::vector类。在这个示例中,我们向pair中的第一个vector添加了三个x坐标,向第二个vector添加了三个y坐标。最后,我们遍历vector pair的元素,并打印出点的坐标。要访问vector pair的元素,我们使用std::pair类的first和second成员。这些成员分别指向pair中的第一个vector和第二个vector。然后,我们可以使用通常的索引语法来访问向量的各个元素。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程