vector的定义以及常见操作

#include "pch.h"
#include <iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
	//一:vector对象初始化,容器可以存储不同的值
	vector<vector<string>> p;

	vector<int> jihe;//没有元素
	vector<int> jihe1(10);//有10个元素
	vector<int> jihe2{ 10,20 };//有两个元素,分别为10,20
	jihe = jihe1;

	vector<string> jihe3;//没有元素
	vector<string> jihe4(10);//有10个元素
	vector<string> jihe5{ "sjfh","sfhsk" };//
	vector<string> jihe6{ 10 };//有10个元素
	//往集合里追加元素
	jihe3.push_back("snfk");
	jihe3.push_back("snfkt");

	jihe4 = jihe5;
	vector<string> jihe7=jihe3;//有10个元素

	//二:vector的操作
	//(1).empty() 判断是否为空 返回bool值

	if (jihe3.empty())
	{
		cout << "jihe3为空" << endl;
	}

	//(2).push_back()//往末尾追加元素

	for (int i = 1; i <=10; i++)
	{
		jihe1.push_back(i);
	}
	//(3).size() 返回元素个数

	cout << jihe1.size() << endl;

	//(4).clear() 清空元素个数

	jihe1.clear();
	cout << jihe1.size() << endl;

	//(5)v[n]返回元素个数 0<=n<size
	
	cout << jihe2[1] << endl;

	//(6)赋值
	vector <int> ivec;
	ivec.push_back(10);//追加元素
	ivec = jihe2;//覆盖原来的10,把jihe2的值给ivec

	//(7)== != 判断两个容器是否相等,类型和元素个数和元素位置的值也相等

	vector<int> a(100);
	vector<int> b(100);

	if (a == b)
	{
		cout << "a==b" << endl;
	}

	//(8)范围for语句在vector中的应用

	vector<int> txj{ 1,2,3,4,5 };

	for (auto x : txj)
	{
		cout << x << endl;
	}

	for (auto &x : txj)//通过应用修改txj里的值
	{
		x = x * 2;
	}
	//已修改txj里面的值
	for (auto x : txj)
	{
		cout << x << endl;
	}
	/*
	for (auto x : txj)
	{
		txj.push_back(55);
		cout << x << endl;//不能在遍历的时候添加元素或者clear因为在遍历时系统已经记住了最后一个值,当遇到它的时候便推出循环
	}
	*/
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值