c++ - comparing objects of class in a vector using operator overloading
问题描述
so I have a class A - parent and B - child, i also have a class c thats unrelated that holds a vector of child objects. Im trying to sort the vector using a compare function in class A that uses operator overloading and having diffcultly making this comparison this is the a.hpp and a.cpp combined
class c; //forward declare
class a{
a();
setfunc(string name){names=name}; //added names to vector
getFunc(){return names};
//use in other class
friend bool compare(const a& A,const a& A1) //would like to compare vector element object
if(A.name == A1.name)
{
return false;
}
if(A.name > A1.name)
{return true;}
if(A.name < Al.name)
{return false;}
else
return false;
}
friend bool operator==(const a& A,const a& A1)
{return A.names == A1.names};
friend bool operator<(const a& A,const a& A1)
{return A.names < A1.names};
friend bool operator>(const a& A,const a& A1) //im using the operators bcuz my understanding it is good practice to use with compare function
//and its a way to compare objects
{return A.names > A1.names};
friend class c;
private:
string names;
}
theres another class b which inherited all the variables thats all done done correct, then class c holds the vector
#include "a.hpp"
class c
class c{
c();
setVec(const a& A)
{
A.getFunc(); //pushing objects into vector
vec.push_back(A);
}
Vecsort(const a& A,const a& A1) //not sort algo
{
for(int i = 0; i < vec.size();i++)
{
if(compare(A,A1) == true) // how would i sent this vec[i] and vec[i+1] through there
{
swap(A,A1) // to be received by the compare func
i = 0 ; //because currently the only thing it compares is the last
//object that was set
}
private:
vector<b> vec; //child of a objects
}
TLDR, have 3 class, a - parent , b - child . c - friend. Ive initialized all parent objects through the child class in main using set func's and sent it to the friend class to sort in a vector, how do i successfully sent a vector element object to that compare() function to be compared? do i need a [] operator or do i need to change the params in the compare() to take a const vector<b&> object?
解决方案
推荐阅读
- angular - 使用 Observable 闪烁 *ngIf 的内容
- swift - 更改 NSVisualEffectView 的颜色
- angular - protractor 2.5.4 E/launcher - 未创建会话:此版本的 ChromeDriver 仅支持 Chrome 版本 79
- ethereum - 无法将 Dapp 部署到 rinkeby
- laravel - Laravel:为什么 composer update 改变了 AuthenticatesUsers 特征的 username() 函数?
- arrays - 如何在 Vue.js 中收集没有重复的嵌套数据?
- javascript - 为什么 Quill 过滤其内容?
- sql - 从循环中选择具有相似名称但添加了增量编号的表列表
- nvidia - 尝试使用 nvidia 光线跟踪扩展程序跟踪三角形时得到一个立方体
- shell - shell中的大制表符分隔文件操作