在一行中初始化一对向量

问题描述:

我想用k对象初始化一个std :: vector(std :: pair)对象,并使用如下所示的一对值。在一行中初始化一对向量

这里是我的尝试:

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

错误:

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>&}’ 
+0

你在一个地方使用'点:: FT'和裸'FT'在另一个 - 你的意思是使用'点:: FT '在std :: numeric_limits'模板中? – cdhowie 2014-09-10 23:13:51

+0

好点@cdhowie。可能在文件中使用了Point :: FT,但错过了它。 :) – gsamaras 2014-09-10 23:14:25

您可以直接切换到{}在构造周围或参数...

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

看到它运行here

+1

哦,是啊!这正是我想要做的,但是使用了括号! – gsamaras 2014-09-11 01:23:03

+1

@ G.Samaras:从C++ 11开始一直使用'{}'是一个好主意 - 有时候额外的东西将会起作用/歧义将被避免,并且它也会处理所有的旧案例...... – 2014-09-11 01:32:17

+0

我接受这个答案,因为它更现代。 – gsamaras 2014-09-11 01:34:21

假设Point::FT是后话,这numeric_limits::max()是有效的,

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