Vector使用总结

Vector使用总结



前言

模板类vector是一种动态数组,此篇用于总结它的常用方法。

使用vector

/* 需要导入头文件 */
#include <vector>

/* 通过命名空间 */
std::vector<Type> ...

/* 或者 using编译指令 */
using namespace std;
vector<Type> ...

/* 又或者 using声明 */
using std::vector;
vector<Type> ...

除了int,string,float等C++基本数据类型外,vector也支持存放我们自己设计的数据类型,但此时需要有对应的构造函数才能保证vector正常使用(尤其是拷贝构造函数)。简单示例如下:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Student {
   
private:
    string name;
    int age;
    long id;
public:
    Student(string name, int age, long id):
            name(name), age(age), id(id)
    {
   }
    Student(const Student& std) {
     /* 拷贝构造函数 */
        name = std.name;
        age = std.age;
        id = std.id;
    }

    friend ostream& operator<< (ostream& os, const Student& std);
};

ostream& operator<< (ostream& os, const Student& std)
{
   
    return os << "{ " << std.name << " "
              << std.age << " " << std.id << " }";
}

int main()
{
   
    vector<Student> stdV = {
   {
   "zty", 22, 20140010}, {
   "you", 23, 20140011}};

    vector<Student> stdV2(stdV);

    cout << stdV2[0] << endl;
    cout << stdV2[1] << endl;
    return 0;
}
// 输出:
{
    zty 22 20140010 }
{
    you 23 20140011 }

容器构造

以下,利用构造函数构造容器。

1. 直接声明一个容器,此时容器为空,不能试图访问容器内部,否则段错误(Segmentation fault)。

vector<int> intV
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值