[英]How to pass from array to vector - c++
I'm new in c++ programming and I'm trying to understand better the differences between array and vector. 我是C ++编程的新手,我试图更好地理解数组和向量之间的区别。 In my program I've got a class Graph with some arrays as private members. 在我的程序中,我有一个带有某些数组的Graph类作为私有成员。 The class has a method that use these arrays to implement the Prim's algorithm for minimum spanning tree. 该类具有使用这些数组来实现最小生成树的Prim算法的方法。 I took the algorithm from this page and changed it for my program. 我从此页面上提取了算法,并为我的程序进行了更改。
I am now asked to use vectors instead of arrays so I would like to know: 现在,我被要求使用向量而不是数组,所以我想知道:
How many things do I really have to change? 我真的必须改变几件事? The declaration and the constructors, ok. 声明和构造函数,好的。 But the cycles, the initializations. 但是循环,初始化。 Do I have to change everything? 我需要改变一切吗? The program works anyway. 该程序仍然可以运行。 Is it so important to use vector's function? 使用向量的函数是如此重要吗?
It should be very simple to switch from arrays to a vector
. 从数组切换到vector
应该非常简单。 You could initialise the vector
with the size of your array and fill it with 0
elements: 您可以使用数组的大小初始化vector
,并用0
元素填充它:
vector<YourType> v(size_of_array, YourType(0));
and then use v
more or less as you used your array, ie: 然后在使用数组时或多或少使用v
,即:
v[x] = YourType(y);
// ....
f(v[z]);
etc 等等
I took a look at the code at your link above and spotted quite a few places where STL vectors can be used rather than the arrays that are defined. 我在上面的链接中查看了一下代码,并发现了可以使用STL向量而不是定义的数组的很多地方。
For example, below is an example of how to replace a couple of the arrays with vectors, and then initialize their values: 例如,下面是一个示例,说明如何用向量替换几个数组,然后初始化它们的值:
#include <iostream>
#include <limits>
#include <vector>
// Number of vertices in the graph
static const int V = 5;
int main()
{
// Rather than use:
// int key[V];
// bool mstSet[V];
// You could setup STL vector containers:
std::vector<int> key;
std::vector<bool> mstSet;
// Next, initialize:
for (size_t i = 0; i < V; i++) {
key.push_back(INT_MAX);
mstSet.push_back(false);
std::cout << key[i] << "; " << mstSet[i] << std::endl;
}
return 0;
}
如果要坚持使用当前的实现,但想尝试使用向量,则可以通过以下方式用数组数据填充向量:
vec.assign(arr, arr + arr_size);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.