0

for example, I can hardcode array as parameter like that:

void test(pair<string,int> v[],int size){
    for(int i=0;i<size;i++){
        printf("%s %d\n",v[i].first.c_str(),v[i].second);
    }
}

int main(){
    test((pair<string,int>[]){make_pair("a",1),make_pair("b",2)},2);
    return 0;
}

so that I don't need to create a temp variable of pair v[] and then no need to worry about the variable name of the temp variable, is there any similar syntax if using vector:

void test(vector<pair<string,int> > v){
    for(pair<string,int> p : v){
        printf("%s %d\n",p.first.c_str(),p.second);
    }
}

?

ggrr
  • 7,737
  • 5
  • 31
  • 53

1 Answers1

6

Because C++11 introduced list initialization with the help of std::initializer_list (not to be confused with constructor initializer lists), you can indeed use a std::vector (which has been modified to have a constructor accepting std::initializer_list) and you can simply do

test({{"a",1), {"b",2}});
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621