Ошибка компилятора c2676

#c #list #struct #compiler-errors

#c #list #struct #compiler-errors

#c #Список #структура #ошибки компилятора

Вопрос:

Я пытаюсь проверить, есть ли уже элемент с таким же значением внутри списка структур, поэтому, если его нет, я возвращаю в список новую структуру.Рассматривайте это как систему с учетными записями, и если учетная запись уже есть, я не хочу снова добавлять ее в список.

Вот мой код в основном:

 accounts test;
test.bal = 0;
test.id = 0;
std::list <accounts> accs;
std::list<accounts>::iterator check;
 

Вот мой код за пределами main:

 #include <list>
#include <iterator>
#include <algorithm>
struct accounts {
    long id;
    int bal;

};
 

Вот мой код внутри цикла for:

  check = find(accs.begin(), accs.end(), test.id);
        if (check == accs.end()) {
            accs.push_back(test);
        }
 

Когда я запускаю код, я получаю ошибку компилятора :

Ошибка C2676 двоичный файл ‘==’: ‘accounts’ не определяет этот оператор или преобразование в тип, приемлемый для предопределенного оператора bankacc C:Program Файлы (x86)Microsoft Visual Studio2019 Сообщество VCИнструменты MSVC14.28.29333 включить xutility 5440

Я видел другие потоки, и я думаю, что мне нужно сделать

 if(check == accs.id.end())
 

или что-то в этом роде, но это не работает, отображается ошибка:

Ошибка (активная) E0135 класс «std::list<учетные записи, std::распределитель>» не имеет члена «id»

Есть идеи? 🙂

Комментарии:

1. Я думаю, мне нужно сделать как-то не угадать, компилятор показывает вам точную строку.

2. @S.M. позвольте мне улучшить мой вопрос

3. if(check == accs.id.end()) неверно или является решением.

4. Становится очень запутанным читать код, который использует существительные во множественном числе для единственных вещей. Если тип представляет учетную запись, назовите его «учетная запись», а не «учетные записи».

5. @molbdnilo когда я удаляю часть внутри цикла for, код работает, и да, мне жаль, что вы правы насчет имен переменных, я забыл их изменить

Ответ №1:

std::find принимает объект того же типа, что и типы в вашем контейнере, которые вы хотите найти, в качестве последнего аргумента. В вашем случае вам следует использовать std::find_if вместо:

 check = find_if(accs.begin(), accs.end(),
    [amp;test](const autoamp; ac) {
      return ac.id == test.id;
    });
 

Комментарии:

1. большое вам спасибо, что сработало. Не могли бы вы объяснить, что на самом деле сделано здесь после [amp;test] ? (На самом деле это сработало, но не подтолкнуло структуру) @johnmastroberti

2. В коде используется лямбда-выражение: https://en.cppreference.com/w/cpp/language/lambda

3. Последний аргумент также find_if является функцией, которая должна возвращаться true при выполнении условия, которое вы хотите найти. Я добился этого здесь с помощью лямбда (бит от [amp;test] до конечной фигурной скобки). Подробнее об этом можно прочитать здесь . Код, который я опубликовал, только заменяет ваш вызов find . Вам все еще нужны последние три строки, которые у вас были, где вы возвращаете новую учетную запись, если она не была найдена.

4. @johnmastroberti ооо, хорошо, большое тебе спасибо. Я полагаю, что обычно для accs размер = 4456540? Потому что я поставил его на просмотр, и это тот размер, который он мне дает

5. Я думаю, вам, вероятно, следует задать отдельный вопрос об этом.

Ответ №2:

Причина довольно проста. Когда вы используете std::find , под капотом происходит что-то вроде этого,

 for(iterator i = begin; i != end; i  )
    if(*i == check) return i;
 

Глядя на это, вы можете видеть, что когда мы передаем ваш список, тип итератора — это std::list<accounts>::iterator то, против чего вы проверяете accounts::id . Способа сделать это нет.

Итак, какие есть варианты? У вас есть 3,

  1. Создайте == оператор для accounts структуры.
  2. Просто перейдите test к тестированию.
  3. Передайте функцию для выполнения сравнения.

Первый простой, вы можете скопировать и вставить это, если хотите,

 struct accounts {
    long id;
    int bal;
    
    bool operator==(const longamp; otherID) const { return id == otherID; }
};
 

Теперь, когда std::find вызывается == оператор, он знает, что делать.

Третий простой, используйте лямбда-выражение.

 check = find(accs.begin(), accs.end(), [amp;test](const accountsamp; other) {
      return other.id == test.id; });
if (check == accs.end()) {
    accs.push_back(test);
}
 

Комментарии:

1. Значит, оба списка должны быть итераторами?

2. Извините, я по ошибке опубликовал неправильный ответ (наполовину завершен). Я отредактировал его.

3. Для первой ошибки Error C2679 binary '==': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion) bankacc C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.28.29333includexutility 5440 и для 3-й она выдает ту же ошибку, что и раньше

4. @TheCodingGuy я ввел const accountsamp; там, где это должно быть const longamp; . Извините, я исправил это.

5. Спасибо, что исправлена ошибка, но по какой-то причине структура не нажимается и получает числа, которые она не должна, вероятно, это моя ошибка где-то спасибо, хотя

Ответ №3:

Просто перегрузите оператор «==». В параметрах выберите желаемый тип значения, которое вы хотите.

  • Remove From My Forums
  • Вопрос

  • Hi everybody,

    I’m getting this compilation error:

    error C2676: binary ‘[‘ : ‘const std::list<_Ty>’ does not define this operator or a conversion to a type acceptable to the predefined operator

    I’m trying to make a list of a union. The union is defined this way, inside a class called CComboBoxControl:

    typedef union unComboBoxData
        {
            int intData;
            unsigned int uintData;
            long longData;
            unsigned long ulongData;
            void* ptrData;
        } tyComboBoxData;

    And the list this way, as a private member of the same class:

    std::list<CComboBoxControl::tyComboBoxData> m_lData;

    I get the error when I try to assign a list’s item to a variable, like this (third line here):

    CComboBoxControl::tyComboBoxData res;
    int curSel =  ComboBox_GetCurSel(m_hWnd);
    res = m_lData[curSel];

    Does anybody know what’s going on?

    Thanks,
    -Sergi Díaz

Ответы

  • Hello Sergi,

    1. std::list don’t have [] operator.
    2. If you need [] operator then another option is std::vector.
      1. But, remember that vector is not as fast as list, when you count insertion/deletion performance.

    Regards,
    Jijo.
    _____________________________________________________

    http://weseetips.com[^] Visual C++ tips and tricks. Updated daily.

    • Помечено в качестве ответа

      16 марта 2009 г. 11:46

    • Изменено
      Jijo Raj
      16 марта 2009 г. 11:50
      changed sentence

  • Forum
  • General C++ Programming
  • C2676 error in Visual 2019 C++H

C2676 error in Visual 2019 C++H

Hello!

I keep getting this error no matter what I change and I can solve it

Error C2676 binary ‘==’: ‘tipAplicatie’ does not define this operator or a conversion to a type acceptable to the predefined operator UnitTests C: 25

My code:
class Autoturism
{
public:
string marca;
string model;
char numarInmatriculare[9];
int putere;
double pret;

You need to provide the compilable code that produces the error. Your ‘code’ is just the start of a class.

This is the code I wrote

#include <iostream>
#include <string>
using namespace std;
bool fisierDeschis = true;

enum class tipAplicatie {
aplicatieWeb = 5,
aplicatieMobila = 10,
aplicatieDesktop = 15,
NONE = 0,
};

class Autoturism
{
public:
string marca;
string model;
char numarInmatriculare[9];
int putere;
double pret;

class Autoturism()
{

marca = «Necunoscuta»;
model = «Necunoscut»;
putere = 0;
pret = 5000;
}

Autoturism(string marca, string model, int putere)
{
this->marca =marca;
this->model = model;
this->putere = putere;
pret = 5000;
}

void discount(int procent)
{
if (procent >= 1 && procent <= 50)
{
pret = pret * (procent / 100.0);
}
}

void seteazaNumarInmatriculare(char numar[])
{
if (strlen(numar) <= 9)
{
strcpy_s(numarInmatriculare, numar);
}
}

char* obtineNumarInmatriculare()
{
return numarInmatriculare;
}
~Autoturism()
{
fisierDeschis = false;
}
};

This is the UniTest code where the error appear a

tipAplicatie rezultat = modificare_enum(«aplicatieWeb»);
Assert::IsTrue(rezultat == 5, L»Functia nu seteaza corect o aplicatie web»);
rezultat = modificare_enum(«aplicatieMobila»);
Assert::IsTrue(rezultat == 10, L»Functia nu seteaza corect o aplicatie mobila»);
rezultat = modificare_enum(«aplicatieDesktop»);
Assert::IsTrue(rezultat == 15, L»Functia nu seteaza corect o aplicatie desktop»);
}

1
2
3
4
5
6
7
class Autoturism()
{
marca = "Necunoscuta";
model = "Necunoscut";
putere = 0;
pret = 5000;
}

This is supposed to be the default constructor. You don’t need the class modifier. All you need is:

1
2
3
4
5
6
7
Autoturism()
{
marca = "Necunoscuta";
model = "Necunoscut";
putere = 0;
pret = 5000;
}

I modified and I still get the same error
It might be something on the code? Or in the UnitTest cpp?

Last edited on

1
2
tipAplicatie rezultat = modificare_enum("aplicatieWeb");
Assert::IsTrue(rezultat == 5, L"Functia nu seteaza corect o aplicatie web");

You can’t compare an enum with an int.
Try this:

 
Assert::IsTrue(rezultat == tipAplicatie::aplicatieWeb , L"Functia nu seteaza corect o aplicatie web");

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <string>
using namespace std;
bool fisierDeschis = true;

enum class tipAplicatie {
    aplicatieWeb = 5,
    aplicatieMobila = 10,
    aplicatieDesktop = 15,
    NONE = 0,
};

class Autoturism
{
public:
    string marca;
    string model;
    char numarInmatriculare[9];
    int putere;
    double pret;
    
    
    Autoturism() // <--
    {
        
        
        marca = "Necunoscuta";
        model = "Necunoscut";
        putere = 0;
        pret = 5000;
    }
    
    Autoturism(string marca, string model, int putere)
    {
        this->marca =marca;
        this->model = model;
        this->putere = putere;
        pret = 5000;
    }
    
    void discount(int procent)
    {
        if (procent >= 1 && procent <= 50)
        {
            pret = pret * (procent / 100.0);
        }
    }
    
    void seteazaNumarInmatriculare(char numar[])
    {
        if (strlen(numar) <= 9)
        {
            strcpy(numarInmatriculare, numar); // <--
        }
    }
    
    char* obtineNumarInmatriculare()
    {
        return numarInmatriculare;
    }
    ~Autoturism()
    {
        fisierDeschis = false;
    }
};

int main()
{
    Autoturism au;
    au.discount(5);
    
    std::cout << au.marca << 'n';
    return 0;
}

Necunoscuta
Program ended with exit code: 0

againtry where you put //<— means I should add something?

No, where I put a //<— means where I fixed your program so it compiles and runs.

thank you very much

Topic archived. No new replies allowed.

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора c2064
  • Ошибка компилятора c2039
  • Ошибка компас 2146762487
  • Ошибка компаньон консоли xbox 0x409
  • Ошибка компа reboot and select proper boot device при запуске