c ++向量库_C ++中的2D向量–实用指南2D向量

本文介绍了C++中2D向量的基础知识,包括如何通过包含Vector头文件来使用2D向量,初始化2D向量的不同方法,如指定大小,以及如何使用迭代器进行遍历、添加和删除元素。2D向量在创建矩阵和处理二维数据结构时非常有用。
摘要由CSDN通过智能技术生成

c ++向量库

Also referred to as vector of vectors, 2D vectors in C++ form the basis of creating matrices, tables, or any other structures, dynamically. Before arriving on the topic of 2D vectors in C++, it is advised to go through the tutorial of using single-dimensional vectors in C++.

也称为向量的向量,C ++中的2D向量构成动态创建矩阵,表或任何其他结构的基础。 在讨论C ++中的2D矢量主题之前,建议先阅读在C ++中使用一维矢量的教程。

包括Vector头文件 (Including the Vector header file)

It would be impossible for us to use vectors in C++, if not for the header files that are included at the beginning of the program. To make use of 2D vectors, we include:

如果没有C ++中的头文件,对于我们来说就不可能使用C ++中的向量。 为了利用2D向量,我们包括:


#include<vector>

Instead of including numerous kinds of Standard Template Libraries (STL) one by one, we can include all of them by:

与其一一包括许多种标准模板库(STL),我们不如通过以下方式将它们全部包括在内:


#include<bits/stdc++.h>


在C ++中初始化2D向量 (Initializing 2D vectors in C++)

Firstly, we will learn certain ways of initializing a 2-D vector. The following code snippet explains the initialization of a 2-D vector when all the elements are already known.

首先,我们将学习初始化二维矢量的某些方法。 以下代码段说明了所有元素都已知时的二维矢量初始化。


#include<iostream>
#include<vector>
using namespace std;

int main(){
	vector<vector<int>> v {
   {1, 0, 1}, {0, 1}, {1, 0, 1}}; 
	for(int i=0;i<v.size();i++){
		for(int j=0;j<v[i].size();j++)
			cout<<v[i][j]<<" ";
		cout<<endl;
	}					   
}

After running the above code, we get the following output:

运行上面的代码后,我们得到以下输出:


1 0 1 
0 1 
1 0 1 

The use of 'vector<vector<>>' symbolizes that we are working on a vector of vectors. Each value inside the first set of braces, like '{1, 0, 1}' and '{0, 1}' are vectors independently.

'vector<vector<>>'表示我们正在研究矢量的向量。 第一组大括号内的每个值(例如'{1, 0, 1}' 1,0,1 '{1, 0, 1}''{0, 1}'都是独立的向量。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值