【问题标题】:Is there any syntax to hardcode vector as parameter?是否有任何语法将向量硬编码为参数?
【发布时间】:2015-08-07 06:48:30
【问题描述】:

例如,我可以像这样将数组硬编码为参数:

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[] 的临时变量,然后无需担心临时变量的变量名,如果使用向量,是否有类似的语法:

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

?

【问题讨论】:

  • 你可以使用std::initializer_list来初始化一个std::vector
  • 在 C++11 中,只需 test({{"a", 1}, {"b", 2}})
  • 你的参数是指针,不是数组。
  • 另外,复合文字在 C++ 中不是一个东西,所以你的代码是无效的。见stackoverflow.com/questions/28116467/…

标签: c++ syntax


【解决方案1】:

因为 C++11 在std::initializer_list 的帮助下引入了list initialization(不要与constructor initializer lists 混淆),所以您确实可以使用std::vector(已修改为具有constructor 接受std::initializer_list) 你可以这样做

test({{"a",1), {"b",2}});

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2011-02-11
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 2016-04-05
    • 1970-01-01
    相关资源
    最近更新 更多