【问题标题】:no instance of overloaded function "search" matches the argument list没有重载函数“search”的实例与参数列表匹配
【发布时间】:2019-07-16 20:22:11
【问题描述】:

我的搜索功能存在以下问题。 它需要 3 个参数,其中一个类似于 constrational_t* v。我想通过该参数传递一个向量,但它似乎不起作用..

代码:

#include <iostream>
#include <cmath>
#include <vector>
#include "rational_t.hpp"

using namespace std;

bool search(const rational_t* v, const int n, const rational_t& x)
{
    for(int i = 0; i < n; i++) {
        if(v[i].value() == x.value()) {
            return true;
        } else {
            return false;
        }
    }
};

int main()
{
    rational_t a(1, 2), b(3), c, d(1, 2);
    vector<rational_t> v;

    v.push_back(a);
    v.push_back(b);
    v.push_back(c);

    cout << "a.value()= " << a.value() << endl;
    cout << "b.value()= " << b.value() << endl;
    cout << "c.value()= " << c.value() << endl;

    cout << search(v, v.size(), d); // Problem here

    return 0;
}

我也试过 cout

有什么想法吗?谢谢。

班级:

#pragma once

#include <iostream>
#include <cassert>
#include <cmath>

#define EPSILON 1e-6

using namespace std;

class rational_t
{
  int num_, den_;

public:
  rational_t(const int = 0, const int = 1);
  ~rational_t() {}

  int get_num() const
  {
    return num_;
  }

  int get_den() const
  {
    return den_;
  }

  void set_num(const int n)
  {
    num_ = n;
  }

  void set_den(const int d)
  {
    assert(d != 0), den_ = d;
  }

  double value(void) const;
  rational_t opposite(void) const;
  rational_t reciprocal(void) const;

  bool equal(const rational_t &r, const double precision = EPSILON) const;
  bool greater(const rational_t &r, const double precision = EPSILON) 
const;
  bool less(const rational_t &r, const double precision = EPSILON) const;
  bool cero_equal(const double precision) const;

  void write(ostream &os = cout) const;
  void read(istream &is = cin);
};

【问题讨论】:

    标签: c++ class pointers vector reference


    【解决方案1】:

    search 的第一个参数应该是 rational_t*,但您传递的是 vector&lt;rational_t&gt;

    你想要

    search(v.data(), v.size(), d)
    

    而不是

    search(v, v.size(), d)
    

    但我会这样写,IMO 更干净:

    bool search(vector<rational_t> & v, const rational_t& x)
    {
      for (int i = 0; i < v.size(); i++) {
        if (v[i].value() == x.value()) {
          return true;
        }
        else {
          return false;
        }
      }
    }
    
    ...
    cout << search(v, d);
    

    【讨论】:

    • 成功了!谢谢你。但我不明白.. 那是因为指针还是因为没有 .data 它无法到达向量的内容?
    • std::vector&lt;Foo&gt;Foo* 不同。但是std::vector&lt;Foo&gt;::data() 是,它返回指向向量第一个元素的指针。
    • 知道了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多