(C++基础_STL) —— vector 类的基本应用

Posted 赵萱婷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(C++基础_STL) —— vector 类的基本应用相关的知识,希望对你有一定的参考价值。

文章目录

(C++基础_STL) —— vector类的基本应用

     在日常的C++开发过程中,我们会经常使用到STL最为赋能加速开发的一个基本库,那么在有一定的C++的语言的基础上,学习如何使用STL是一件非常有益与后续有益于自己面对更加复杂的需求和日常开发赋能的,因此,本人虽然工作了有一段时日了,准备开始写一系列专栏记录自己重温STL的一些用法,并加深自己对于STL的理解和运用的过程,本系列文章主要用于自己复习和参考使用,如果您看到感兴趣了也可以跟我一并一起进一步学习和探讨。

     个人编写的项目地址如下:UsingSTLEx

0 个人介绍

作者: 赵萱婷
简介: 一个在工业软件领域摸爬滚打的新人,毕业于华科软院的一个普通人,希望未来能够在工业设计软件领域深耕越走越远的软件工程师。
个人格言:用心去感受你自己需要坚持的生活,未来慢慢会给你答案的。
知乎:https://www.zhihu.com/people/Tom_Zhao
STL项目地址: https://gitee.com/zhaotianyuCoding/using-stlex

vector容器

1. vector的基本概念

     基础功能:

  • vector数据结构和数组非常相似,也称为单端数组。

     vector与普通数组区别:

  • 不同之处在于数组是静态空间,而vector可以动态扩展。

     所谓的动态扩展:

  • 并不是在原空间之后续接新空间,而是找更大的内存空间,然后将原数据拷贝新空间,释放原空间。

2. vector的构造函数

     vector的构造函数主要用于创建vector容器本身,只是会存在不同的集中创建方式,具体的函数原型有如下一些:

  • vector<T> v; //采用模板实现类实现,默认构造函数
  • vector(v.begin(), v.end()); //将v[begin(), end())区间中的元素拷贝给本身。
  • vector(n, elem); //构造函数将n个elem拷贝给本身。
  • vector(const vector &vec); //拷贝构造函数。

     具体相关项目的CMakeLists.txt如下:

#[================================================================[.rst:
    Copyright (c)2021, Tom Zhao personal. ("UsingSTLEx")
    This software is a personal tools project by Tom Zhao.
    Description:
#]================================================================]

set(TZ_MAIN_NAME VectorConstructor)

set(TZ_MAIN_INCLUDE

)

set(TZ_MAIN_INC

)

set(TZ_MAIN_SRC
	main.cpp
)

add_executable($TZ_MAIN_NAME
	$TZ_MAIN_INCLUDE
	$TZ_MAIN_INC
	$TZ_MAIN_SRC
)

set_property(TARGET $TZ_MAIN_NAME PROPERTY FOLDER "UsingVector")

     具体相关项目的代码如下,放在VectorConstrutor项目里面:


///
// Copyright (c) 2021, Tom Zhao personal. ("UsingSTLEx")
// This software is a personal tools project by Tom Zhao.
// Description:
///

#include <iostream>
#include <vector>

using namespace std;

// print the vector for show.
void printVector(vector<int>& v)

	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
		cout << *it << " ";
	
	cout << endl;


void TzVectorConstructorCase01()

	vector<int> v1; // constructor without any param.
	for (int i = 0; i < 10; i++) 
		v1.push_back(i);
	
    
	printVector(v1);

    // constructor with param with a certain vector's start and end.
	vector<int> v2(v1.begin(), v1.end());
	printVector(v2);

    // constructor with param with range.
	vector<int> v3(10, 100);
	printVector(v3);
	
    // constructor with param with a certain vector.
	vector<int> v4(v3);
	printVector(v4);


int main(int argc, char *argv[])

	TzVectorConstructorCase01();

	system("pause");
	return 0;

3. vector的赋值操作

     赋值操作的主要作用是给已有的vector容器进行赋值或者直接覆盖的操作,具体可能用到的函数原型有:

  • vector& operator=(const vector &vec);//重载等号操作符

  • assign(beg, end); //将[beg, end)区间中的数据拷贝赋值给本身。

  • assign(n, elem); //将n个elem拷贝赋值给本身。

     对于赋值操作个人所编写的示例如下:

CMakeLists:

#[================================================================[.rst:
    Copyright (c)2021, Tom Zhao personal. ("UsingSTLEx")
    This software is a personal tools project by Tom Zhao.
    Description:
#]================================================================]

set(TZ_MAIN_NAME VectorOperator)

set(TZ_MAIN_INCLUDE

)

set(TZ_MAIN_INC

)

set(TZ_MAIN_SRC
	main.cpp
)

add_executable($TZ_MAIN_NAME
	$TZ_MAIN_INCLUDE
	$TZ_MAIN_INC
	$TZ_MAIN_SRC
)

set_property(TARGET $TZ_MAIN_NAME PROPERTY FOLDER "UsingVector")

     所对应的代码在VectorOperator项目中,具体的代码如下:


///
// Copyright (c) 2021, Tom Zhao personal. ("UsingSTLEx")
// This software is a personal tools project by Tom Zhao.
// Description:
///

#include <iostream>
#include <vector>

using namespace std;

void printVector(vector<int>& v)

	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
		cout << *it << " ";
	
	cout << endl;


// operator=
void TzVectorOperatorCase01()

	vector<int> v1;
	for (int i = 0; i < 10; i++) 
		v1.push_back(i);
	
    
	printVector(v1);

	vector<int>v2;
	v2 = v1;
	printVector(v2);

	vector<int>v3;
	v3.assign(v1.begin(), v1.end());
	printVector(v3);

	vector<int>v4;
	v4.assign(10, 100);
	printVector(v4);


// other operators.
void TzVectorOperatorCase02()

	std::vector<int> alice1, 2, 3;
    std::vector<int> bob7, 8, 9, 10;
    std::vector<int> eve1, 2, 3;
 
    std::cout << std::boolalpha;
 
    // Compare non equal containers
    std::cout << "alice == bob returns " << (alice == bob) << '\\n';
    std::cout << "alice != bob returns " << (alice != bob) << '\\n';
    std::cout << "alice <  bob returns " << (alice < bob) << '\\n';
    std::cout << "alice <= bob returns " << (alice <= bob) << '\\n';
    std::cout << "alice >  bob returns " << (alice > bob) << '\\n';
    std::cout << "alice >= bob returns " << (alice >= bob) << '\\n';
 
    std::cout << '\\n';
 
    // Compare equal containers
    std::cout << "alice == eve returns " << (alice == eve) << '\\n';
    std::cout << "alice != eve returns " << (alice != eve) << '\\n';
    std::cout << "alice <  eve returns " << (alice < eve) << '\\n';
    std::cout << "alice <= eve returns " << (alice <= eve) << '\\n';
    std::cout << "alice >  eve returns " << (alice > eve) << '\\n';
    std::cout << "alice >= eve returns " << (alice >= eve) << '\\n';


int main()

	TzVectorOperatorCase01();
	TzVectorOperatorCase02();

	system("pause");
	return 0;

     对于赋值操作,常用的还是直接使用=,用assign的方式可能比较少。

4. vector的容量和大小

     对于容量和大小,主要是用来操作和获取当前vector容器能够容纳多少个项目和具体现在拥有多少个项的大小的,具体使用到的相关函数的原型如下:

  • empty(); //判断容器是否为空

  • capacity(); //容器的容量

  • size(); //返回容器中元素的个数

  • resize(int num); //重新指定容器的长度为num,若容器变长,则以默认值填充新位置。//如果容器变短,则末尾超出容器长度的元素被删除。

  • resize(int num, elem); //重新指定容器的长度为num,若容器变长,则以elem值填充新位置。​ //如果容器变短,则末尾超出容器长度的元素被删除

     对应项目的CMakeLists文件如下:

#[================================================================[.rst:
    Copyright (c)2021, Tom Zhao personal. ("UsingSTLEx")
    This software is a personal tools project by Tom Zhao.
    Description:
#]================================================================]

set(TZ_MAIN_NAME VectorCapacity)

set(TZ_MAIN_INCLUDE

)

set(TZ_MAIN_INC

)

set(TZ_MAIN_SRC
	main.cpp
)

add_executable($TZ_MAIN_NAME
	$TZ_MAIN_INCLUDE
	$TZ_MAIN_INC
	$TZ_MAIN_SRC
)

set_property(TARGET $TZ_MAIN_NAME PROPERTY FOLDER "UsingVector")

     该项目代码叫VectorCapacity,可以看到示例代码为:


///
// Copyright (c) 2021, Tom Zhao personal. ("UsingSTLEx")
// This software is a personal tools project by Tom Zhao.
// Description:
///

#include <iostream>
#include <vector>

using namespace std;

void printVector(vector<int>& v)

	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) 
		cout << *it << " ";
	
	cout << endl;


// operator=
void TzVectorCapacityCase01()

	vector<int> v1;
	for (int i = 0; i < 10; i++)
	
		v1.push_back(i);
	
	printVector(v1);
	if (v1.empty())
	
		cout << "v1 is null" << endl;
	
	else
	
		cout << "v1 is not null" << endl;
		cout << "v1's capacity = " << v1.capacity() << endl;
		cout << "v1's size = " << v1.size() << endl;
	

	// Resize re specifies the size. If the specified size is larger,
	// the new location is filled with 0 by default. You can replace the default filling with the overloaded version
	v1.resize(15,10);
	printVector(v1);

	// Resize re specifies the size. If the specified size is smaller, the excess elements will be deleted
	v1.resize(5);
	printVector(v1);


// other use ways.
void TzVectorCapacityCase02()

	// using empty()
	// empty() returns true if the vector is empty, otherwise false.
    std::cout << std::boolalpha;
    std::vector<int> numbers;
    std::cout << "Initially, numbers.empty(): " << numbers.empty() << '\\n';
 
    numbers.push_back(42);
    std::cout << "After adding elements, numbers.empty(): " << numbers.empty() << '\\n';

	// using size()
	// size() returns the number of elements in the vector.
	// size() is a member function of the vector class.
	// size() is a non-const member function.
	std::vector<int> nums 1, 3, 5, 7;
    std::cout << "nums contains " << nums.size() << " elements.\\n";

	// using max_size()
	// The max_size() function returns the maximum number of elements that can be stored in the vector.
	std::vector<char> s;
    std::cout << "Maximum size of a 'vector' is " << s.max_size() << "\\n";

	// using capacity()
	// capacity() returns the number of elements that the container has currently allocated space for.
	// capacity() does not change the size of the container.
	int sz = 200;
    std::vector<int> v1;
 
    auto cap = v1.capacity();
    std::cout << "initial capacity=" << cap << '\\n';
 
    for (int n = 0; n < sz; ++n)
	
        v1.push_back(n);
        if (cap != v1.capacity())
		
            cap = v1.capacity();
            std::cout << "new capacity=" << cap << '\\n';
        
    
 
    std::cout << "final size=" << v1.size() << '\\n';
    std::cout << "final capacity=" << v1.capacity() << '\\n';
	
	// using shrink_to_fit()
	// shrink_to_fit() is a member function of vector class.
	// shrink_to_fit() is used to reduce the capacity of the vector to the actual size of the vector.
	// shrink_to_fit() is useful when you know that the vector will not be resized in the future.
	std::vector<int> v;
    std::cout << "Default-constructed capacity is " << v.capacity() << '\\n';
    v.resize(100);
    std::cout << "Capacity of a 100-element vector is " << v.capacity() << '\\n';
    v.resize(50);
    std::cout << "Capacity after resize(50) is " << v.capacity() << '\\n';
    v.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\\n';
    v.clear();
    std::cout << "Capacity after clear() is " << v.capacity() << '\\n';
    v.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\\n';
    for (int i = 1000; i < 1300; ++i)
        v.push_back(i);
    std::cout << "Capacity after adding 300 elements is " << v.capacity() << '\\n';
    v.以上是关于(C++基础_STL) —— vector 类的基本应用的主要内容,如果未能解决你的问题,请参考以下文章

(C++基础_STL) —— vector 类的基本应用

(C++基础_STL) —— vector 类的基本应用

(C++基础_STL) —— string类的基本应用

(C++基础_STL) —— string类的基本应用

(C++基础_STL) —— string类的基本应用

(C++基础_STL) —— string类的基本应用