如何使用std :: vector :: emplace_back for vector< vector< int> >? [英] how to use std::vector::emplace_back for vector<vector<int> >?

查看:473
本文介绍了如何使用std :: vector :: emplace_back for vector< vector< int> >?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  vector<vector<int> > res;
  res.emplace_back({1,2}); // change to res.push_back({1,2}); would work

这给我错误

main.cpp:61:25: error: no matching function for call to ‘std::vector<std::vector<int> >::emplace_back(<brace-enclosed initializer list>)’
main.cpp:61:25: note: candidate is:
In file included from /usr/include/c++/4.7/vector:70:0,
                 from /usr/include/c++/4.7/bits/random.h:34,
                 from /usr/include/c++/4.7/random:50,
                 from /usr/include/c++/4.7/bits/stl_algo.h:67,
                 from /usr/include/c++/4.7/algorithm:63,
                 from miscalgoc.hpp:1,
                 from main.cpp:1:
/usr/include/c++/4.7/bits/vector.tcc:92:7: note: void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {}; _Tp = std::vector<int>; _Alloc = std::allocator<std::vector<int> >]

如何使这项工作?另外,为什么在这里需要分配器?

How to make this work? Also, why an allocator is needed here?

推荐答案

问题是函数模板参数不会导出 std :: initializer_list 从一个braced-init-list(如 {1,2} )。

The problem is that function template arguments doesn't deduce std::initializer_list from a braced-init-list (like { 1, 2 }).

/ p>

Example:

#include <initializer_list>
#include <type_traits>


template<typename T>
void func(T arg) {
}


int main() {
    auto init_list = {1, 2};    // This works because of a special rule
    static_assert(std::is_same<decltype(init_list), std::initializer_list<int>>::value, "not same");

    func(std::initializer_list<int>{1, 2});     // Ok. Has explicit type.

    func({1, 2});   // This doesn't because there's no rule for function
                    //      template argument to deduce std::initializer_list
                    //      in this form.
}

实例

std :: vector :: emplace_back() 是一个函数模板,它的参数被推导出来。因此,传递 {1,2} 将无法工作,因为它无法推导出来。为其添加显式类型

std::vector::emplace_back() is a function template with its arguments being deduced. So passing it {1, 2} will not work because it couldn't deduce it. Putting an explicit type to it

res.emplace_back(std::initializer_list<int>{1,2});

会使其正常工作。

a href =http://coliru.stacked-crooked.com/a/ef151ed35da1e4d0>实例

Live example

这篇关于如何使用std :: vector :: emplace_back for vector&lt; vector&lt; int&gt; &gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆