C++中map和vector作形参时如何给定默认参数?

时间:2022-03-31 07:42:04

map和vector都可以用operator[]进行访问,map是用[]中的数据作为key进行查询,而vector是用[]中的数作为下标进行访问。

如果在用operator[]进行访问的时候出现了越界情况,即map没有这个键值对,或vector的大小小于下标数值,会发生什么情况?

?
1
2
3
4
5
6
7
8
9
10
11
struct node{int a{5};};
int main() {
  map<string,node> m1;
  cout<<m1["s"].a<<endl;
  map<string,int> m2;
  cout<<m2["s"]<<endl;
  vector<node> v1(3);//需要指定vector大小,否则不能在没有push_back的情况用下标访问
  cout<<v1[0].a<<endl;
  vector<int> v2(3);
  cout<<v2[0];
}

结果:

5
0
5
0

由上面示例程序可看出map和vector在越界情况都会给出此类型的默认值,如果是基本类型,则返回零值;如果是struct或class,如果里面的变量定义了默认值,则返回定义的默认值,如果没有,返回零值。

之前遇到过这种特殊场景, 我用static变量比较恶心地解决了问题, 其实, 有更优雅的方式:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
 int a = int();
 cout << a << endl;
 vector<int> v = vector<int>();
 for(vector<int>::iterator it = v.begin(); it != v.end(); ++it)
 {
 cout << *it << endl;
 }
 return 0;
}

看下: 

?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
using namespace std;
void fun(int a, int b = 1, const vector<int> &v=vector<int>()) // 此处的const不能少,v也必须初始化(因为左边参数已经默认初始化)
{
}
int main ()
{
 fun(1);
 cout << "to end" << endl;
 return 0;
}

不多说。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/stpeace/article/details/79967053