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}'都是独立的向量。

Note: To create 2D vectors in C++ of different data-type, we can place the data-type inside the innermost angle brackets like <char>.

注意 :要在C ++中创建不同数据类型的2D向量,我们可以将数据类型放在最里面的尖括号内,例如<char>

Since we are working on a two-dimensional data structure, we require two loops for traversing the complete data structure, efficiently. The outer loop moves along the rows, whereas the inner loop traverses the columns.

由于我们正在研究二维数据结构,因此需要两个循环才能有效遍历完整的数据结构。 外循环沿行移动,而内循环横穿列。

Note: The 'size()' function provides the number of vectors inside the 2D vector, not the total number of elements inside each individual vectors.

注意: 'size()'函数提供2D向量内向量的数量,而不是每个单独向量内的元素总数。

指定2D向量初始化的大小 (Specifying the size for 2D Vector Initialization)

2D vectors can be of large sizes. We can not expect the programmer to feed-in every single value. Therefore, we can initialize a 2-D vector on the basis of the number of rows and columns.

2D向量的大小可能很大。 我们不能期望程序员输入每个值。 因此,我们可以根据行数和列数来初始化二维矢量。


#include<iostream>
#include<vector>
using namespace std;int main(){//Number of columnsint num_col = 3;// Number of rowsint num_row = 4;// Initializing a single rowvector<int> row(num_col, 0);// Initializing the 2-D vectorvector<vector<int>> v(num_row, row) ;for(int i=0;i<v.size();i++){for(int j=0;j<v[i].size();j++)cout<<v[i][j]<<" ";cout<<endl;}
}

The output would be:

输出为:


0 0 0
0 0 0
0 0 0
0 0 0

According to the standard initialization of a vector,'vector<int> v(10, 0)', the first argument denotes the size of the vector whereas the second denotes the default value every cell holds.

根据向量的标准初始化'vector<int> v(10, 0)' ,第一个参数表示向量的大小,而第二个参数表示每个单元格所保存的默认值。

In the above code snippet, we follow two steps of standard initialization:

在上面的代码片段中,我们遵循标准初始化的两个步骤:

  • 'vector<int> row(num_col, 0)' – In this statement, we create a single-dimensional vector called 'row', which has length defined by 'num_col' and default values as '0'. It basically forms each row of our two-dimensional vector.'vector<int> row(num_col, 0)' –在此语句中,我们创建一个名为'row'一维向量,其长度由'num_col'定义,默认值为'0' 。 它基本上形成了二维矢量的每一行。
  • 'vector<vector<int>> v(num_row, row) – In this statement, we create our complete two-dimensional vector, by defining every value of the 2-D vector as the 'row' created in the last statement.'vector<vector<int>> v(num_row, row) –在此语句中,我们将二维矢量的每个值定义为在上一条语句中创建的'row' ,从而创建了完整的二维矢量。

After understanding the above procedure, we can improve our initialization of 2D vectors in C++ by:

了解了上述过程之后,我们可以通过以下方法改进C ++中2D向量的初始化:


#include<iostream>
#include<vector>
using namespace std;int main(){//Number of columnsint num_col = 3;// Number of rowsint num_row = 4;// Initializing the 2-D vectorvector<vector<int>> v(num_row, vector<int> (num_col, 0)) ;for(int i=0;i<v.size();i++){for(int j=0;j<v[i].size();j++)cout<<v[i][j]<<" ";cout<<endl;}
}

The above code, will provide the similar output as before, since we are doing the exact same thing, but in a single line of code.

上面的代码将提供与以前相似的输出,因为我们正在做完全相同的事情,但是只用一行代码。

If we remember correctly, the standard initialization looks somewhat like the above one. Creating a two-dimensional vector requires us to set the default value for every element as a single-dimensional vector.

如果我们没记错的话,标准初始化看起来与上面的类似。 创建二维向量需要我们将每个元素的默认值设置为一维向量。

The last method involves creating a 2-D vector without the knowledge of rows or columns. It is done by:

最后一种方法涉及在不知道行或列的情况下创建二维矢量。 通过以下方式完成:


vector<vector<int>> v;

The above declaration creates an empty container capable of storing elements in the form of vectors.

上面的声明创建了一个空容器,该容器能够存储矢量形式的元素。



2D向量的迭代器 (Iterators for 2D vectors)

Instead of traversing a 2D vector using indices, C++ has a provision of iterators for every specific STL data structure.

除了使用索引遍历2D向量之外,C ++还为每个特定的STL数据结构提供了迭代器。


#include<iostream>
#include<vector>
using namespace std;int main(){vector<vector<int>> v {{1, 0, 1}, {0, 1}, {1, 0, 1}}; // Iterator for the 2-D vectorvector<vector<int>>::iterator it1;// Iterator for each vector inside the 2-D vectorvector<int>::iterator it2;// Traversing a 2-D vector using iteratorsfor(it1 = v.begin();it1 != v.end();it1++){for(it2 = it1->begin();it2 != it1->end();it2++)cout<<*it2<<" ";cout<<endl;}
}

Output:

输出:


1 0 1
0 1
1 0 1

The iterators come in handy when we use certain operations that require an argument for positioning. The two most used functions returning iterator values are:

当我们使用某些需要参数进行定位的操作时,迭代器会派上用场。 返回迭代器值的两个最常用的函数是:

  • 'v.begin()' – It returns an iterator to the first vector in a 2-D vector.'v.begin()' –将迭代器返回到二维向量中的第一个向量。
  • 'v.end()' – It returns an iterator to the end of the 2-D vector.'v.end()' –将迭代器返回到二维向量的末尾。

Let us look at some operations possible on a 2-D vector.

让我们看看在二维矢量上可能进行的一些操作。



将元素添加到二维向量 (Adding elements to a 2-D vector)

To add elements at the end of a two-dimensional vector, we use 'push_back()' function.

要在二维向量的末尾添加元素,我们使用'push_back()'函数。


#include<iostream>
#include<vector>
using namespace std;int main(){// Initializing the 2-D vectorvector<vector<int>> v;v.push_back({1, 0, 1});v.push_back({0, 1});v.push_back({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;}
}

Output:

输出:


1 0 1
0 1
1 0 1

Since our container is a vector of vectors, it would only make sense to push complete vectors inside it. Therefore, the argument passed inside the 'push_back()' function must be a vector.

由于我们的容器是向量的向量,因此将完整的向量推入其中是有意义的。 因此,在'push_back()'函数内部传递的参数必须是向量。

Note: 'v[i]' represents a single-dimensional vector. Therefore, if the programmer needs to add elements in a certain vector inside the 2-D vector, he may use 'v[i].push_back(value)'.

注意: 'v[i]'表示一维向量。 因此,如果程序员需要在2-D向量内的某个向量中添加元素,则可以使用'v[i].push_back(value)'

To add a complete vector at a specific location, we use the 'insert()' function.

要在特定位置添加完整的向量,我们使用'insert()'函数。


#include<iostream>
#include<vector>
using namespace std;int main(){// Initializing the 2-D vectorvector<vector<int>> v;v.push_back({1, 0, 1});v.push_back({0, 1});v.push_back({1, 0, 1});// Iterator for the 2-D vectorvector<vector<int>>::iterator it = v.begin();// Inserting the vector = {1, 2, 3} as the second vectorv.insert(it + 1, {1, 2, 3});for(int i=0;i<v.size();i++){for(int j=0;j<v[i].size();j++)cout<<v[i][j]<<" ";cout<<endl;}
}

Output:

输出:


1 0 1
1 2 3
0 1
1 0 1

The 'insert()' function requires a positional argument as an iterator not as an integral index. It is followed by a vector that is supposed to be inserted at the specified location.

'insert()'函数需要使用位置参数作为迭代器,而不是整数索引。 它后面是一个应该在指定位置插入的向量。



在C ++中从2D向量中删除元素 (Removing elements from 2D vectors in C++)

Opposite to the 'push_back()', C++ provides 'pop_back()' function with the duty of removing the last element from the given vector.

'push_back()'相反,C ++提供了'pop_back()'函数,其职责是从给定的向量中删除最后一个元素。

In the context of this article, 'pop_back()' function would be responsible for removing the last vector from a 2-D vector.

在本文的上下文中, 'pop_back()'函数将负责从二维矢量中删除最后一个矢量。


#include<iostream>
#include<vector>
using namespace std;int main(){// Initializing the 2-D vectorvector<vector<int>> v ;// Adding vectors to the empty 2-D vectorv.push_back({1, 0, 1});v.push_back({0, 1});v.push_back({1, 0, 1});// Remove the last vector from a 2-D vectorv.pop_back();for(int i=0;i<v.size();i++){for(int j=0;j<v[i].size();j++)cout<<v[i][j]<<" ";cout<<endl;}
}

Output:

输出:


1 0 1
0 1

In addition to the 'pop_back()' function, we have an 'erase()' function using which we can remove elements from a specified index.

除了'pop_back()'函数外,我们还有一个'erase()'函数,通过它可以从指定的索引中删除元素。


#include<iostream>
#include<vector>
using namespace std;int main(){// Initializing the 2-D vectorvector<vector<int>> v ;// Pushing vector inside the empty 2-D vectorv.push_back({1, 0, 1});v.push_back({0, 1});v.push_back({1, 0, 1});// Iterator for the 2-D vectorvector<vector<int>>::iterator it = v.begin();// Remove the second vector from a 2-D vectorv.erase(it + 1);for(int i=0;i<v.size();i++){for(int j=0;j<v[i].size();j++)cout<<v[i][j]<<" ";cout<<endl;}
}

Output:

输出:


1 0 1
1 0 1

Similar to the 'insert()' function, it requires a positional argument as an iterator. To remove all the vectors from the 2-D vector, 'clear()' function can be used.

'insert()'函数类似,它需要一个位置参数作为迭代器。 要从二维矢量中删除所有矢量,可以使用'clear()'函数。

The above functions might be enough to get comfortable while using 2-D vectors in C++.

在C ++中使用2-D向量时,上述功能可能足以使您感到舒适。



结论 (Conclusion)

Two-dimensional vectors in C++ are very easy to use, provided that the programmer is aware of the syntax involved. This kind of vector comes in handy when we solve problems related to matrices, graphs, and other two-dimensional objects.

如果程序员知道所涉及的语法,则C ++中的二维向量非常易于使用。 当我们解决与矩阵,图和其他二维对象有关的问题时,这种矢量非常有用。

We hope that this tutorial enlightened the reader on the topic of using 2-D vectors. Feel free to comment below for any queries related to the topic.

我们希望本教程对使用2-D向量的主题有所启发。 对于与该主题相关的任何查询,请在下面随意评论。

翻译自: https://www.journaldev.com/42023/2d-vectors-in-c-plus-plus

c ++向量库

c ++向量库_C ++中的2D向量–实用指南2D向量相关推荐

  1. c++ 的 stl模板库_C ++中的标准模板库(STL)

    c++ 的 stl模板库 Standard Template Library (STL) is a collection of standard C++ template classes. It co ...

  2. c++ windows 蓝牙库_c++中蓝牙编程的库类

    展开全部 安装PSDK就可以用了62616964757a686964616fe59b9ee7ad9431333330343239,之前有写过一个类在MFC里面调用,并能成功与蓝牙手机通信,只不过是非标 ...

  3. linux chroot_Linux中chroot命令的实用指南

    linux chroot Sometimes, you may need to isolate a process from other processes running on your syste ...

  4. as点击发送广播_Apache Flink 中广播状态的实用指南

    翻译 | 王柯凝 校对 | 邱从贤(山智) 自版本 Flink 1.5.0 以来,Apache Flink 提供了一种新的状态类型,称为广播状态(Broadcast State).在本文中,将解释什么 ...

  5. 简短加密_神经网络训练中回调的简短实用指南

    简短加密 Callbacks are an important part of neural network training. These are actions that can be perfo ...

  6. c ++向量库_在C ++中对2D向量进行排序

    c ++向量库 As per as a 2D vector is concerned it's a vector of a 1D vector. But what we do in sorting a ...

  7. c ++向量库_将向量复制到C ++中的另一个向量

    c ++向量库 The ways that we are using to copy vectors in C++, are: 我们用于在C ++中复制向量的方法是: Copy one vector' ...

  8. c++中的向量_C ++中的向量

    c++中的向量 A Vectors in C++ is an array-like container that can change dynamically in size. Being a par ...

  9. 在Keras的Embedding层中使用预训练的word2vec词向量

    文章目录 1 准备工作 1.1 什么是词向量? 1.2 获取词向量 2 转化词向量为keras所需格式 2.1 获取所有词语word和词向量 2.2 构造"词语-词向量"字典 2. ...

最新文章

  1. MVC、MVP和MVVM的优缺点
  2. DeepMind推出首个商业产品,30秒内准确诊断眼疾!
  3. unity的vr场景怎么做_营销技巧逐渐失效,如何通过场景化营销重新赢回市场?...
  4. Plugin [id: 'org.jetbrains.kotlin.jvm'] was not found in any of the following sources:
  5. gcc -strip编译选项的作用
  6. 卷积法求解系统的零状态响应_动态系统的建模与分析
  7. java boolean 包_java Boolean包装类工作笔记
  8. 马斯克喊话库克:昨天你对我爱答不理,今天我让你高攀不起
  9. 涂鸦赞助的500个开发套件,先到先得
  10. android网速代码,Android获取网速和下载速度
  11. 软件设计(中线提取)
  12. luogu 3373 线段树懒标记维护乘与加
  13. 与众不同 独树一帜,传智播客2018春季课程发布会在京举行
  14. 前端将后端返回的文件流转为excel并下载
  15. matplotlib只显示部分横坐标刻度,隐藏部分横坐标刻度
  16. 解决 Java 加载 pfx 报密码错误
  17. 项目经理如何提升核心竞争力,给自己增值
  18. 《男女诗篇》 - 肖复兴
  19. CSS3 弹性盒布局模型和布局原理
  20. html自动下拉框怎么做,html下拉菜单怎么做?

热门文章

  1. 批处理mysql命令
  2. Oracle性能优化技巧
  3. [转载] 消除vscode安装pylint后提示的unused variable
  4. [转载] 交互式数据可视化在Python中用Bokeh实现
  5. [转载] python计时函数timeit.timeit()使用小结
  6. verilog读入.txt的有符号十进制数,把有符号十进制数写入到.txt文件中
  7. iOS直播集成和问题总结(阿里云直播)
  8. CentOS7发布ASP.NET Core网站
  9. python之路 《四》 字典
  10. 程序员“不会”修电脑的原因