【问题标题】:How to display maximum element of vector<myStruct>?如何显示vector<myStruct>的最大元素?
【发布时间】:2020-06-02 11:45:33
【问题描述】:

我有一个源代码,内容如下:

#include <iostream> 
#include <algorithm> 
#include <vector>
using namespace std; 

struct st
{
    int id;
    double d;
}; 

bool comp(int a, int b) 
{ 
    return (a < b); 
} 

bool comp2(st &a, st& b) { return a.d < b.d; }

int main() 
{
    vector<int> v = { 9, 4, 7, 2, 5, 15, 11, 12, 1, 3, 6 };
    vector<st> vec = {{1, 5.6},{2, 5.7},{3, 4.3}};

    auto max = std::max_element(v.begin(), v.end(), comp);
    cout << "Max element of v: " << *max; // It's working

    auto max2 = std::max_element(vec.begin(), vec.end(), comp2);
    cout << "Max element of vec: " << *max2; // It's not working

    return 0; 
}

当我尝试显示向量 vec 的最大值时,出现以下错误:

[Error] cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'

问题的可能解决方案是什么?

【问题讨论】:

  • 1) 这不是一个完整的错误消息。 2)您的st 没有定义operator&lt;&lt; (std::ostream&amp;, st const&amp;),因此不能用operator &lt;&lt; 打印(相关,可能:How to properly overload the << operator for an ostream?
  • 提示:尝试一次只专注于一件事。您当前的问题不是向量,也不是最大值。 st x; std::cout &lt;&lt; x; 会出现类似的错误。代码越少,修复就越容易

标签: c++ algorithm vector operator-overloading max


【解决方案1】:

您没有为struct st 类型的对象定义运算符

cout << "Max element of vec: " << *max2;

相反,你可以写例如

cout << "Max element of vec: " << max2->id << ", " << max2->d << '\n';

或者您为 struct st 类型的对象冷定义运算符

std::ostream & operator <<( std::ostream &os, const st &obj )
{
    return os << "( " << obj.id << ", " << obj.d << " )";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多