C/C++vector容器的使用

注意:

int N = 5;
vector<int>arr(N);  // 这是创建一个拥有5个int 类型数据的 vector类

int N = 5;
vector<int>arr{N}; // 这是初始化arr的元素为a[0] = 5; 元素个数为1
#include <iostream>
#include <vector>
#include <string>
using namespace std;

void Print(const vector<string>& temp)
{
	for (size_t i = 0; i < temp.size(); i++)
	{
		cout << temp[i] << " ";
	}

	cout << endl;
}


int main()
{
	// 0.0 vector容器,肯定有很多的重载的构造函数,也包含拷贝构造函数。
	// 模板类,类型的自动推到--C++17以后引入的
	vector<string>words1 = { "hello","world","C PLUSPLUS","Come on","Baby" };
	cout << "words1: ";
	Print(words1);

	// 1.0 删除最后一个元素--words1.end()指向的是最后一个元素的结尾。所以删除最后一个元素要减1
	words1.erase(words1.end() - 1);
	cout << "words1: ";
	Print(words1);

	// 2.0 追加元素--push_back--不必多言

	// 3.0 用迭代器拷贝words1的元素,以创建words2---也可以从某个地方,到某个地方的拷贝
	vector<string>words2{ words1.begin(), words1.end() };
	cout << "words2: ";
	Print(words2);

	// 4.0 在words2中插入元素:(例如在第二个元素后插入)
	words2.insert(words2.begin() + 2, "77777777");
	cout << "words2: ";
	Print(words2);

	// 5.0 用拷贝构造函数,拷贝words2 的元素给 words3;
	vector<string>words3{ words2 };
	cout << "words3: ";
	Print(words3);

	// 6.0 用[]修改words3的元素;
	words3[2] = "888888888";
	cout << "words3: ";
	Print(words3);

	// 7.0 创建words4, 初始化为多个相同的字符串:
	vector<string>words4(4, "hello");
	cout << "words4: ";
	Print(words4);

	// 8.0 交换words3 和 words4
	words3.swap(words4);
	cout << "words3: ";
	Print(words3);


	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值