How to give default parameters when C++ map and vector are used as formal parameters?

  • 2020-06-15 09:50:20
  • OfStack

Both map and vector can be accessed with operator[], map with data in [] as key, and vector with Numbers in [] as subscripts.

What happens if an out-of-bounds condition occurs when accessing with operator[], that is, map does not have this key-value pair, or that vector is smaller than the subscript value?


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);// You need to specify the vector Size otherwise cannot be in without push_back Is accessed with a subscript  
  cout<<v1[0].a<<endl;
  vector<int> v2(3);
  cout<<v2[0];
}

Results:

[

5
0
5
0

]

As you can see from the above sample program, both map and vector give the default value of this type when they cross the boundary. If it is a basic type, zero is returned. If it is struct or class, it returns the default value defined if the variable inside defines the default value, or zero if it does not.

In this particular case, I've used the static variable to solve the problem in a rather nasty way, but there's a more elegant way:


#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;
}

Take a look at:


#include <iostream>
#include <vector>
using namespace std;
void fun(int a, int b = 1, const vector<int> &v=vector<int>()) //  Here the const Cannot little, v Must also be initialized ( Because the left argument is initialized by default )
{ 
}
int main ()
{
 fun(1);
 cout << "to end" << endl;
 return 0;
}

Not much said.

conclusion


Related articles: