【问题标题】:Sorting an Vector of Objects with std::sort使用 std::sort 对对象向量进行排序
【发布时间】:2019-05-30 15:49:48
【问题描述】:

我是 C++ 新手。我想对向量 Konto 类型的向量“Konten”进行排序。

我搜索了一个解决方案并找到了 std::sort 函数。我已经为“Konto”类重载了 operator

错误 C2678 二元运算符“=”:找不到运算符 接受“const account”左操作数(或正确的转换是 不可能)c:\程序文件(x86)\微软视觉工作室\ 2017\community\vc\tools\msvc\14.15.26726\include\ 算法3835

//KontenManager.h
#pragma once

#include "Konto.h"
#include <vector>

class Kontenmanager
{
private:
    vector<Konto> Konten;

public:
    Kontenmanager();
    ~Kontenmanager();
    string getKontenListe() const;
};

//Kontenmanager.cpp
#include "pch.h"
#include "Kontenmanager.h"
#include <sstream>
#include <algorithm>
#include <iomanip>


Kontenmanager::Kontenmanager()
{
}


Kontenmanager::~Kontenmanager()
{
}


string Kontenmanager::getKontenListe() const
{
    stringstream out;
    sort(Konten.begin(), Konten.end());            //<----------- Here is my problem

//do some stuff

}

//Konto.h
#pragma once

#include <string>

using namespace std;

class Konto
{
private:
    int kontoNr;
    double saldo;
    string inhaber;
    int pin;

public:
    Konto(int Kontonummer, string inhaber, int pin);
    ~Konto();
    int getKontonummer() const;
};

bool operator<(const Konto &k1, const Konto &k2);
bool operator==(const Konto &k1, const Konto &k2);

//Konto.cpp
#include "pch.h"
#include "Konto.h"


Konto::Konto(int Kontonummer, string inhaber, int pin) :kontoNr(Kontonummer)
{
    this->kontoNr = Kontonummer;
    this->inhaber = inhaber;
    this->pin = pin;
    this->saldo = 0.0;
}


Konto::~Konto()
{
}

int Konto::getKontonummer() const
{
    return kontoNr;
}

bool operator<(const Konto &k1, const Konto &k2)
{
    return k1.getKontonummer() < k2.getKontonummer();
}

bool operator==(const Konto &k1, const Konto &k2)
{
    return k1.getKontonummer() == k2.getKontonummer();
}

【问题讨论】:

  • const int kontoNr; 替换为int kontoNr; 并删除const 限定符getKontenListe
  • 关闭问题的原因根本不合适,期望的行为很明显:编译没有错误,我们必须重现问题
  • @drescherjm,第一,Konto 不可赋值,第二,在getKontenListe 中你不能更改Konten
  • 我已经更改了 const 属性但仍然是同样的问题
  • @BaummitAugen 我从问题中复制了 50 行以具有类和操作定义,并添加 10 行以具有主要填充向量排序并编写它,我真的不明白你,但无论如何,OP得到纠正,这是主要的,有一个很好的延续

标签: c++ sorting object vector


【解决方案1】:

当您在 Visual Studio 中出现错误时,您可以按计算机键盘上的 F1 来获取有关该错误的帮助。

任何开发者都应该知道 google.com 在搜索框中输入 C2678 并按 Enter。

这是文档:

https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-2/compiler-error-c2678?view=vs-2019

答案:删除其他人提到的额外const 说明符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 2018-10-18
    相关资源
    最近更新 更多