是否有将向量硬编码为参数的语法?
Is there any syntax to hardcode vector as parameter?
例如,我可以像这样将数组硬编码为参数:
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;
}
这样我就不需要创建 v[] 对的临时变量,然后就不用担心临时变量的变量名了,如果使用 vector:[=12= 有没有类似的语法]
void test(vector<pair<string,int> > v){
for(pair<string,int> p : v){
printf("%s %d\n",p.first.c_str(),p.second);
}
}
?
因为 C++11 引入了 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 接受 std::initializer_list
) 而你可以简单地做
test({{"a",1), {"b",2}});
例如,我可以像这样将数组硬编码为参数:
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;
}
这样我就不需要创建 v[] 对的临时变量,然后就不用担心临时变量的变量名了,如果使用 vector:[=12= 有没有类似的语法]
void test(vector<pair<string,int> > v){
for(pair<string,int> p : v){
printf("%s %d\n",p.first.c_str(),p.second);
}
}
?
因为 C++11 引入了 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 接受 std::initializer_list
) 而你可以简单地做
test({{"a",1), {"b",2}});