The features of Vector in C++

来源:互联网 发布:光纤是如何传输数据的 编辑:程序博客网 时间:2024/04/28 16:29

There are so many containers in C++, like vector, list, map and so on. To be honest, I am always confused with these containers since in my point of view, they are somehow similar. But with no doubt, there still exist differences among them. I try to expose these differences by using my experiences. I will start withvector.

1. In order to use vector, we need to add     

#include <vector>

using namespace std;

in front.

2. How to define a vector

vector<type> v; ////type could be int, double.....

3. How to insert an element

v.push_back(3);

4. Accessing the elements.

Since vector could be regarded as a dynamic array, so we could use index of vector to access the elements. For instance,v[1], v[2].

Alternatively, we could use iterator.

5. Advantanges and Disadvantanges of vector.

Ad: (1) It's easy to access the elements in vector since we could use index.

(2) It's easy to insert element at the end.

Disad: time-consuming to insert or remove element at positions other than the end.



原创粉丝点击