vector的基本操作

定义、初始化
// 初始化
vector<int> ve;	// size为0的vector
vector<int> ve(10);	// size为10,默认值为0
vector<int> ve(10, 1);	// size为10,默认值为1

int a[5] = {1, 2, 3, 4 ,5};
vector<int> ve1(a, a + 5);	// 通过地址初始化
vector<int> ve2(ve1.begin(), ve1.end()); 
 
// 赋值
vector<int> a(10, 1);
vector<int> b(10, 100);
copy(b.begin(), b.begin() + 5, a.begin());	// copy函数
骚操作
sort(s.begin(), s.end(), [&] (const string &s, const string &t) {
        return s.size() < t.size();
    });
遍历vector,下标、迭代器、auto。
vector<int> ve;
//迭代器 
vector<int>::iterator it;
for(it = ve.begin(); it < ve.end(); it++) {
	printf("%d ",*it);
}

// auto
for (auto it : ve) {
	 cou << it << endl;
}
修改元素
  • insert
//在起始位置插入 10 
ve.insert(ve.begin(),10);

//在起始位置插入 2个10 
ve.insert(ve.begin(), 2, 10);

//在起始位置插入 某个区间(地址) 
ve.insert(ve.begin(), ve2.begin(), ve2.end());
  • push_back
// 在vector后插入元素
ve.push_back()
  • pop_back()
// 删除最后一个元素
ve.pop_back()
  • ve.front() 、ve.back() 、ve.clear()

  • erase

//删除某个区间 
ve.erase(ve.begin(), ve.begin() + 1);

//删除某个位置 
ve.erase(ve.begin());
函数
  • accumulate 区域求和; 三个参数,前两个是范围,最后一个是初始值
vector<int> a(10, 1);
int sum = accumulate(a.begin(), a.end(), 0);

vector<string> a(10, "1");
string sum = accumulate(a.begin(), a.end(), string(""));
  • swap() 交换两个vector
swap(ve1, ve2)
ve1.swap(ve2)
```c
- **reverse 翻转**

reverse(ve.begin(), ve.end());

- **find 查找**
```cpp
头文件: #include <algorithm>

// 查找单个元素
vector<int>::iterator it;
it = find(ve.begin(), ve.end(), x);

// vector中查找结构体(重载 == )
- 结构体内部重载
struct ac{
    int x, y;
    bool operator == (const ac & a) {
        return a.x == x && a.y == y;
    }
};
- 结构体外部重载
struct ac{
    int x, y;
};
bool operator == (const ac &a, const ac &b) {
    return a.x == b.x && a.y == b.y;
}
it = find(v.begin(), v.end(), (ac){a, b});

// vector中查找pair(不需要重载 == )
it = find(v.begin(), v.end(), make_pair(a, b));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值