美文网首页
C/C++基础知识(六)——异常、容器、命名空间

C/C++基础知识(六)——异常、容器、命名空间

作者: 王志强_9380 | 来源:发表于2019-10-12 17:11 被阅读0次

异常处理

void test1()
{
    throw "测试!";
}

void test2()
{
    throw exception("测试");
}

try {
    test1();
}
catch (const char *m) {
    cout << m << endl;
}
try {
    test2();
}
catch (exception  &e) {
    cout << e.what() << endl;
}

//自定义
class MyException : public exception
{
public:
   virtual char const* what() const
    {
        return "myexception";
    }
};

//随便抛出一个对象都可以

容器

序列式容器

元素排列顺序和元素本身无关,有添加顺序决定
序列式容器有:vector,list,dequeue,queue,stack,priority queue

vector<int> vec_1;
//声明一个元素空间
vector<int> vec_2(1);
//6个元素,值都是1
vector<int> vec_3(6, 1);

vector<int> vec_4(vec_3);
//增加元素
vec_3.push_back(10);
//通过下表获得元素
cout << "vec_3[6]:" << vec_3[6] << endl;
//直接获取队首和队尾的元素
vec_3.front();
vec_3.back();
//清空容器中的内容,但并不回收内存
vec_3.clear();
//清空容器中的内容以及释放内存,并返回指向删除元素的下一个元素的迭代器
vec_3.erase(vec_3.begin(), vec_3.end());

关联式容器

关联式容器有:set,map,hashmap

set<int> set1 = { 1,2,3,4 };
pair<set<int>::iterator, bool> pair1 = set1.insert(1);
cout << "insert(1) size:" << set1.size() << " 插入返回值:" << pair1.second << endl;
pair<set<int>::iterator, bool> pair2 = set1.insert(5);
cout << "insert(5) size:" << set1.size() << " 插入返回值:" << pair2.second << endl;
//迭代器
set<int>::iterator itt = set1.begin();
for (; itt != set1.end(); itt++) {
    cout << *itt << endl;
}

执行结果:
insert(1) size:4 插入返回值:0
insert(5) size:5 插入返回值:1
1
2
3
4
5

从结果看以看到,set中不能插入已有的值

map<int, string> map1;
map<int, string> map2 = { {1, "A"},{2, "B"} };
map2.insert({3, "C"});

map2[3] = "D";

map<int, string>::iterator it;
for (it = map2.begin(); it != map2.end(); it++) {
    cout << "map2: " << it->first << "  " << it->second <<  endl;
}

执行结果:
map2: 1 A
map2: 2 B
map2: 3 D

tips:在使用cout 输出string的时候,要include <string>,否则会报错

命名空间

namespace first_space {
    void funcnamespace() {
        cout << "namespacetest1" << endl;
    }
}

namespace second_space {
    void funcnamespace() {
        cout << "namespacetest2" << endl;
    }
}


void namespacetest() {
    first_space::funcnamespace();
    second_space::funcnamespace();
}

引用和指针
  • 不存在空引用。引用必须连接到一块合法的内存;
  • 一旦引用被初始化为一个对象,就不能被指向另一个对象;
  • 指针可以在任何时候指向另一个对象
  • 引用必须在创建的时候初始化,指针可以在任何时候被初始化


    引用和指针.png
int i = 17;
int* p = &i;
int& r = i;

cout << "指针 *p=" << *p << endl;
cout << "引用 r=" << r <<endl;

执行结果
指针 *p=17
引用 r=17

相关文章

网友评论

      本文标题:C/C++基础知识(六)——异常、容器、命名空间

      本文链接:https://www.haomeiwen.com/subject/aqcqmctx.html