Initialize a vector of pairs in one line

≡放荡痞女 提交于 2019-11-30 09:38:38

问题


I want to initialize a std::vector (of std::pair), with k objects, with the pair of values shown below.

Here is my attempt:

// int k
std::vector <std::pair<Point::FT, int> >
    v(k, (std::numeric_limits<FT>::max(), -1));

The error:

usr/include/c++/4.6/bits/stl_vector.h: In member function ‘void std::vector<T, Allocator>::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integer = int, _Tp = std::pair<float, int>, _Alloc = std::allocator<std::pair<float, int> >]’:
/usr/include/c++/4.6/bits/stl_vector.h:340:4:   instantiated from ‘std::vector<T, Allocator>::vector(_InputIterator, _InputIterator, const allocator_type&) [with _InputIterator = int, _Tp = std::pair<float, int>, _Alloc = std::allocator<std::pair<float, int> >, std::vector<T, Allocator>::allocator_type = std::allocator<std::pair<float, int> >]’
../Random_kd_tree.h:139:50:   instantiated from ‘void Random_kd_tree<DivisionSpace, Tree>::search_nn(std::vector<float>&, int, std::vector<std::pair<float, int> >&) [with DivisionSpace = Division_Euclidean_space, Tree = RKD<Division_Euclidean_space>]’
../main.cpp:51:30:   instantiated from here
/usr/include/c++/4.6/bits/stl_vector.h:1080:4: error: no matching function for call to ‘std::vector<std::pair<float, int> >::_M_fill_initialize(std::vector<std::pair<float, int> >::size_type, int&)’
/usr/include/c++/4.6/bits/stl_vector.h:1080:4: note: candidate is:
/usr/include/c++/4.6/bits/stl_vector.h:1122:7: note: void std::vector<T, Allocator>::_M_fill_initialize(std::vector<T, Allocator>::size_type, const value_type&) [with _Tp = std::pair<float, int>, _Alloc = std::allocator<std::pair<float, int> >, std::vector<T, Allocator>::size_type = unsigned int, std::vector<T, Allocator>::value_type = std::pair<float, int>]
/usr/include/c++/4.6/bits/stl_vector.h:1122:7: note:   no known conversion for argument 2 from ‘int’ to ‘const value_type& {aka const std::pair<float, int>&}’

回答1:


You can just switch to { } around the constructor arguments...

std::vector<std::pair<Point::FT, int>> v{k, {std::numeric_limits<FT>::max(), -1}};

See it running here




回答2:


Assuming Point::FT is something for which numeric_limits::max() is valid,

std::vector <std::pair<Point::FT, int>>
        v(k, std::make_pair(std::numeric_limits<FT>::max(), -1));


来源:https://stackoverflow.com/questions/25776531/initialize-a-vector-of-pairs-in-one-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!