[英]Copy data of vector<MyStruct> to a pointer of a vector<MyStruct>
[英]How to display maximum element of vector<myStruct>?
我有一個源代碼,其中包含以下內容:
#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>&&'
問題的可能解決方案是什么?
您沒有為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 << " )";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.