【问题标题】:How to pass vector from a class to a function?如何将向量从类传递给函数?
【发布时间】:2014-12-13 20:04:27
【问题描述】:

我有一个班级Point,为了简单起见,它看起来像这样:

template<class DivisionSpace>
class Point {
 public:
  typedef typename DivisionSpace::FT FT;

  const std::vector<FT>* get_coords() const {
    return &coords;
  }
 private:
  std::vector<FT> coords;
};

现在,我想在 main 中将此类的向量传递给期望的函数 std::vector&lt;FT&gt;&amp; q。我传递了一个参考,以避免复制。我可以使用指针,但这意味着我必须更改许多代码行(因为项目的结构)。

我该怎么做? C++11 有什么“技巧”吗?


编辑

这是函数的原型:

void search_nn_prune(std::vector<FT>& q,
                       std::vector<std::pair<float, int> >& res,
                       int max_leaf_check, bool sorted_results = false, int k =
                           1,
                       float epsilon = 0) {

我主要做

  std::vector< Point<Division_space> > q;

  std::vector<std::vector<std::pair<float, int> > > results(Q);
  for(int i = 0; i < Q; ++i) {
    const std::vector<FT>* query = q[i].get_coords();
    kdf.search_nn_prune(query, results[i], max_leaf_check, false, k, epsilon);
  }

这是错误

error: no matching function for call to ‘Random_kd_forest<Division_Euclidean_space<int> >::search_nn_prune(const std::vector<int, std::allocator<int> >*&, std::vector<std::pair<float, int> >&, int&, bool, int&, float&)’
note: candidates are:
note: void Random_kd_forest<DivisionSpace>::search_nn_prune(std::vector<typename DivisionSpace::FT>&, std::vector<std::pair<float, int> >&, int, bool, int, float) [with DivisionSpace = Division_Euclidean_space<int>, typename DivisionSpace::FT = int]
note:   no known conversion for argument 1 from ‘const std::vector<int, std::allocator<int> >*’ to ‘std::vector<int, std::allocator<int> >&’
note: void Random_kd_forest<DivisionSpace>::search_nn_prune(size_t, std::vector<std::vector<std::pair<float, int> > >&, int, bool, int, float) [with DivisionSpace = Division_Euclidean_space<int>, size_t = unsigned int]
note:   no known conversion for argument 2 from ‘std::vector<std::pair<float, int> >’ to ‘std::vector<std::vector<std::pair<float, int> > >&’

【问题讨论】:

    标签: c++ pointers c++11 vector reference


    【解决方案1】:

    问题是您的 search_nn_prune 函数需要一个 vector&lt;FT&gt;&amp; 参数,但您传递给它的是一个 const vector&lt;FT&gt;&amp; 。您不能将对 const 对象的引用传递给需要可修改对象的函数。

    如果search_nn_prune 不应该修改给定的vector&lt;FT&gt;,请将const 添加到函数声明中的参数中。如果 应该修改矢量,您需要决定如何解决这种情况:Point 不允许更改它返回的坐标矢量,但您想要将其传递给将更改坐标的函数。

    通过引用接受参数的函数通常应该采用const 引用,除非该函数打算修改它给定的对象。

    【讨论】:

      【解决方案2】:

      您应该声明函数接受对向量的const 引用

      void search_nn_prune(const std::vector<FT>& q, ...
      

      你可以通过

      kdf.search_nn_prune(*query, ...
      

      (注意 * 取消引用星号)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-21
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        • 2020-09-06
        • 1970-01-01
        • 2011-12-02
        • 1970-01-01
        相关资源
        最近更新 更多