首页 > 编程语言 >【C++】vector-1

【C++】vector-1

时间:2024-09-25 11:21:50浏览次数:3  
标签:std cout iterator int C++ vector include

文章目录

1.vector的介绍及使用

1.1 vector的介绍

1.vector是表示可变大小数组的序列容器。
2.就像数组一样,vector也采用的连续存储空间来存储元素。也就是意味着可以采用下标对vector的元素进行访问,和数组一样高效。但是又不像数组,它的大小是可以动态改变的,而且它的大小会被容器自动处理。
3.本质讲,vector使用动态分配数组来存储它的元素。当新元素插入时候,这个数组需要被重新分配大小为了增加存储空间。其做法是,分配一个新的数组,然后将全部元素移到这个数组。就时间而言,这是一个相对代价高的任务,因为每当一个新的元素加入到容器的时候,vector并不会每次都重新分配大小。
4.vector分配空间策略:vector会分配一些额外的空间以适应可能的增长,因为存储空间比实际需要的存储空间更大。不同的库采用不同的策略权衡空间的使用和重新分配。但是无论如何,重新分配都应该是对数增长的间隔大小,以至于在末尾插入一个元素的时候是在常数时间的复杂度完成的。
5. 因此,vector占用了更多的存储空间,为了获得管理存储空间的能力,并且以一种有效的方式动态增长。
6. 与其它动态序列容器相比(deques, lists and forward_lists), vector在访问元素的时候更加高效,在末尾添加和删除元素相对高效。对于其它不在末尾的删除和插入操作,效率更低。比起lists和forward_lists统一的迭代器和引用更好。学习方法:使用STL的三个境界:能用,明理,能扩展 ,那么下面学习vector,我们也是按照这个方法去学习。

1.2 vector的使用

vector学习时一定要学会查看文档:vector的文档介绍,vector在实际中非常的重要,在实际中我们熟悉常见的接口就可以,下面列出了哪些接口是要重点掌握的。

1.2.1 vector的定义

(constructor)构造函数声明接口声明
vector() (重点)无参构造
vector() (size_type n, const value_type& val = value_type())构造并初始化n个val
vector(const vector& x); (重点)拷贝构造
vector(InputItreator first, InputItreator last);使用迭代器进行初始化构造
//constructing vectors
#include <iostream>
#include <vector>

int main()
{
	//constructors used in the same order as described above:
	std::vector<int> first;    //empty vector of ints
	std::vector<int> second (4, 100);   //four ints with value 100
	std::vector<int> third (second.begin(), second.end());//iterating through second
	std::vector<int> fourth (third); //a copy of third
	
	//下面涉及迭代器初始化的部分,我们学习完迭代器再来看这部分
	//the iterator construtor can also be used to construct from arrays:
	int myints[] = {16, 2, 77, 29};
	std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int));

	std::cout << "The contents of fifth are:";
	for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
		std::cout<< ' ' << *it;
	std::cout << '\n';

	return 0;
}

1.2.2 vector iterator的使用

Iterator的使用接口说明
begin + end (重点)获取第一个数据位置的iterator/const_iterator, 获取最后一个数据的下一个位置的iterator/const_iterator
rbegin + rend获取最后一个数据位置的reverse_iterator, 获取第一个数据前一个位置的reverse_iterator

在这里插入图片描述

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

void PrintVector(const vector<int>& v)
{
	// const对象使用const迭代器进行遍历打印
	vector<int>::const_iterator it = v.begin();
	while(it != v.end)
	{
		cout << *it << " ";
	}
	cout << endl;
}
int main()
{
	//使用push_back插入4个数据
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);

	//使用迭代器进行遍历打印
	vector<int>::iterator it = v.begin();
	while (it != v.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	//使用迭代器进行修改
	it = v.begin();
	while(it != v.end())
	{
		*it *= 2;
		++it;
	}

	//使用反向迭代器进行遍历再打印
	vector<int>::reverse_iterator rit = v.begin();
	while (rit != v.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	PrintVector(v);

	cout << endl;

	PrintVector(v);

	return 0;
}

1.2.3 vector 空间增长问题

容量空间接口说明
size获取数据个数
capacity获取容量大小
empty判断是否为空
resize(重点)改变vector的size
reverse(重点)改变vector放入capacity

1.capacity的代码在vs和g++下分别运行会发现,vs下capacity是按1.5倍增长的,g++是按2倍增长的。这个问题经常会考察,不要固化的认为,顺序表增容都是2倍,具体增长多少是根据具体的需求定义的。vs是PJ版本STL, g++是SGI版本STL。
2.reverse只负责开辟空间,如果确定知道需要用多少空间,reverse可以缓解vector增容的代价缺陷问题。
3.resize在开空间的同时还会进行初始化,影响size。

// vector::capacity
#include <iostream>
#include <vector>
int main ()
{
	size_t sz;
	std::vector<int> foo;
	sz = foo.capacity();
	std::cout << "making foo grow:\n";
	for (int i=0; i<100; ++i) {
		foo.push_back(i);
		if (sz!=foo.capacity()) {
			sz = foo.capacity();
			std::cout << "capacity changed: " << sz << '\n';
 		}
 	}
}
vs:运行结果:
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 3
capacity changed: 4
capacity changed: 6
capacity changed: 9
capacity changed: 13
capacity changed: 19
capacity changed: 28
capacity changed: 42
capacity changed: 63
capacity changed: 94
capacity changed: 141
g++运行结果:
making foo grow:
capacity changed: 1
capacity changed: 2
capacity changed: 4
capacity changed: 8
capacity changed: 16
capacity changed: 32
capacity changed: 64
capacity changed: 128
// vector::reserve
#include <iostream>
#include <vector>
int main ()
{ 	
	size_t sz;
 	std::vector<int> foo;
 	sz = foo.capacity();
 	std::cout << "making foo grow:\n";
	for (int i=0; i<100; ++i) {
 		foo.push_back(i);
 		if (sz!=foo.capacity()) {
 			sz = foo.capacity();
 			std::cout << "capacity changed: " << sz << '\n';
		 }
	 }
 	std::vector<int> bar;
 	sz = bar.capacity();
 	bar.reserve(100); // this is the only difference with foo above
 	std::cout << "making bar grow:\n";
 	for (int i=0; i<100; ++i) {
 		bar.push_back(i);
 		if (sz!=bar.capacity()) {
 			sz = bar.capacity();
 			std::cout << "capacity changed: " << sz << '\n';
 		}
 	}
 	return 0;
}
// vector::resize
#include <iostream>
#include <vector>
int main ()
{
 	std::vector<int> myvector;
 	// set some initial content:
 	for (int i=1;i<10;i++)
 		myvector.push_back(i);
 		
 	myvector.resize(5);
 	myvector.resize(8,100);
 	myvector.resize(12);
 	std::cout << "myvector contains:";
 	for (int i=0;i<myvector.size();i++)
 		std::cout << ' ' << myvector[i];
 		
 	std::cout << '\n';
 	return 0;
}

1.2.4 vector 增删查改

vector增删查改接口说明
push back(重点)尾插
pop back(重点)尾删
find查找。(注意这个是算法模块实现,不是vector的成员接口
insert在position之前插入val
erase删除position位置的数据
swap交换两个vector的数据空间
operator[] (重点)像数组一样访问
//push_back pop_back
#include <iostream>
#include <vector>
using namespace std;

int main()
{
	int a[] = {1, 2, 3, 4};
	vector<int> v(a, a + sizeof(a) / sizeof(int));

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

	it = v.begin();
	while(it != v.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	
	return 0;
}
// find / insert / erase
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	int a[] = {1, 2, 3, 4 };
	vector<int> v(a, a + sizeof(a) / sizeof(int));

	//使用find查找3所在位置的iterator
	vector<int>::iterator pos = find(v.begin(), v.end(), 3);

	//在pos之前插入30
	v.insert(pos, 30);

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

	pos = find(v.begin(), v.end(), 3);
	//删除pos位置的数据
	v.erase(pos);

	it = v.begin();
	while(it != v.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	return 0;
}
//operator[] +index 和C++11中vector的新式for+auto的遍历
//vector使用这两种遍历方式是比较便捷的
#include <iostream>
#include <vector>
using namespace std;

int main()
{
 	int a[] = { 1, 2, 3, 4 };
 	vector<int> v(a, a + sizeof(a) / sizeof(int));
 	// 通过[]读写第0个位置。
 	v[0] = 10;
 	cout << v[0] << endl;
 	// 通过[i]的方式遍历vector
 	for (size_t i = 0; i < v.size(); ++i)
		 cout << v[i] << " ";
	 cout << endl;
	 vector<int> swapv;
 	swapv.swap(v);
	 cout << "v data:";
	 for (size_t i = 0; i < v.size(); ++i)
 		cout << v[i] << " ";
 	cout << endl;
 	cout << "swapv data:";
	 for (size_t i = 0; i < swapv.size(); ++i)
		 cout << swapv[i] << " ";
	 cout << endl;
 
 	// C++11支持的新式范围for遍历
 	for(auto x : v)
		 cout<< x << " ";
	 cout<<endl;
	 return 0;
}

标签:std,cout,iterator,int,C++,vector,include
From: https://blog.csdn.net/m0_46676283/article/details/142423484

相关文章

  • C++模拟真人鼠标轨迹
    一.API跨语言平台支持鼠标轨迹API底层实现采用C/C++语言,利用其高性能和系统级访问能力,开发出高效的鼠标轨迹模拟算法。通过将算法封装为DLL(动态链接库),可以方便地在不同的编程环境中调用,实现跨语言的兼容性。通过DLL封装,开发者可以在C++、Python、易语言、按键精......
  • onnxruntime c++ 推理例子
    资源释放的问题。onnxruntime的对象release是无效的,从接口源码上只是将指针赋空。并未实际释放。要实现释放,需要以指针形式实现。一个例子如下:#include<onnxruntime_cxx_api.h>voidtestimage(){Matimage=imread("ae14.jpg",IMREAD_UNCHANGED); //创建会话选项 O......
  • C++: unordered系列关联式容器
    目录1.unordered系列关联式容器1.1unordered_map1.2unordered_set2.哈希概念3.哈希冲突4.闭散列5.开散列博客主页:酷酷学感谢关注!!!正文开始1.unordered系列关联式容器在C++98中,STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到......
  • C++ Practical-1 day6
    系列文章目录点击直达——文章总目录文章目录系列文章目录C++Practical-1day6Overview1.abstract_class抽象类1.1.抽象类的特点1.2.示例:抽象类1.3.注意事项2.virtual_function虚函数2.1.示例:动物叫声的多态性2.2.示例:计算图形的面积2.3.注意事项关于作者C+......
  • 自梳理C++八股
    1.左右值引用的理解回答:“左右值引用是C++11引入的一项重要特性,用于优化资源管理和提升性能。具体来说:左值引用(LvalueReference):左值引用可以类比为对象的别名,它允许多个引用共享一个实体对象,常用于函数参数传递以避免对象拷贝。左值引用只能绑定到一个命名的持久对象,适合用......
  • 【C++】STL详解之string类
    本次内容大纲:什么是STLSTL(standardtemplatelibaray-标准模板库):是C++标准库的重要组成部分,不仅是一个可复用的组件库,而且是一个包罗数据结构与算法的软件框架。STL的版本原始版本AlexanderStepanov、MengLee在惠普实验室完成的原始版本,本着开源精神,他们声明允许任......
  • C++ IO 类
    IO库:istream(输入流)类型,提供输入操作。ostream(输出流)类型,提供输出操作。cin,一个istream对象,从标准输入读取数据。cout,一个ostream对象,向标准输出写入数据。cerr,一个ostream对象,通常用于输出程序错误消息,写入到标准错误。>>运算符,用来从一个istream对象读取输入数据。<......
  • C++语言的词汇
    关键字关键字:也称保留字,它是由C++语言本身预先定义好的一类单词基本数据类型和布尔类型int、float、double、char、bool:用于声明整型、浮点型、字符型和布尔型变量。true、false:布尔类型的两个字面量值。复杂数据类型与类class:用于声明类,是C++面向对象编程的基础。str......
  • 【C++基础知识——迭代器 引入】
    问题引入#include<iostream>#include<map>#include<string>intmain(){//定义一个std::map容器std::map<std::string,int>ageMap;ageMap["Alice"]=30;ageMap["Bob"]=25;ageMap["Charlie&q......
  • C++基础
    1.第一个C++程序#include<iostream>//固定格式usingnamespacestd;intmain(){inta=10//定义变量;cout<<a<<endl;//打印变量system("pause");return0;}2.常量与变量的类型只要变量前加const与#define(宏常量)3.关键字3......