21xrx.com
2024-06-03 04:41:32 Monday
登录
文章检索 我的文章 写文章
C++中的Vector:二维用法
2023-07-03 05:46:44 深夜i     --     --
C++ Vector 二维 数据结构 编程技巧

C++是一种功能强大的编程语言,它包含了许多有用的数据结构,其中包括Vector。Vector是一个非常有用的数据结构,用于存储不同类型的数据。一个Vector可以被视为一个数组,但是它可以自动扩展自身的大小。在C++中,Vector常用于存储一维数组,但也可以轻松地用于二维数组。在本文的下面一节,我们将讨论Vector在二维中的用法。

以一个简单的例子开始,假设你需要编写一段代码用于存储和管理一个城市的人口数量。每个城市都会有多个街区,每个街区都有不同的人口数量。我们可以使用一个二维Vector来存储这些信息。下面是一些代码片段,用于定义和初始化这个二维Vector:


#include <vector>

#include <iostream>

int main() {

  // define a 2D vector

  std::vector<std::vector<int>> city_population;

  // define the population of each block

  std::vector<int> block1 100;

  std::vector<int> block2 150 ;

  std::vector<int> block3 75;

  // add the blocks to the city population vector

  city_population.push_back(block1);

  city_population.push_back(block2);

  city_population.push_back(block3);

  // output the population of the first block in the second street

  std::cout << city_population[1][0] << std::endl;

  return 0;

}

在这个例子中,我们定义了一个二维Vector,名为city_population。使用push_back()方法,我们将三个街区的人口数量作为一维Vector添加到了city_population中。在代码的最后,我们输出了第二条街道第一个街区的人口数量,这是一个简单的例子说明了二维Vector的基本用法。

更复杂的用法

在上面的代码中,我们使用了一个二维Vector来存储数字。但是在许多情况下,可能需要存储不同类型的数据。在这种情况下,我们可以使用一个结构体或类来存储数据。例如,假设我们需要存储一个城市的人口数量,以及每个街区的名称和地址。我们可以使用以下代码来定义一个结构体:


#include <string>

struct Block

  std::string name;

  std::string address;

  int population;

;

然后,我们可以定义一个二维Vector,用于存储每个街区的信息。下面是一些代码片段,用于定义和初始化这个二维Vector:


#include <vector>

#include <iostream>

struct Block

  std::string name;

  std::string address;

  int population;

;

int main() {

  // define a 2D vector

  std::vector<std::vector<Block>> city_blocks;

  // define the blocks

  std::vector<Block> street1{

     "address1",

     "address2",

     "block3"

  };

  std::vector<Block> street2{

     300 ,

     "address2",

     150

  };

  std::vector<Block> street3{

     "address1",

     75 ,

     100

  };

  // add the streets to the city blocks vector

  city_blocks.push_back(street1);

  city_blocks.push_back(street2);

  city_blocks.push_back(street3);

  // output the population of the second block in the third street

  std::cout << city_blocks[2][1].population << std::endl;

  return 0;

}

在这个例子中,我们定义了一个名为Block的结构体,它包含一个名称、一个地址和一个人口数量。然后,我们定义了一个二维Vector,名为city_blocks。使用push_back()方法,我们将三个街道的信息添加到了city_blocks中。在代码的最后,我们输出了第三条街道第二个街区的人口数量。

结论

在C++中,Vector是一个非常有用的数据结构,可以用于存储不同类型的数据。它可以轻松地用于二维数组的处理。在本文中,我们讨论了Vector的基本用法,以及如何在二维中存储不同类型的数据。对于那些正在使用C++语言进行编程的人来说,理解Vector的用法可以大大提高编写代码的效率。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复