#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,
- Создайте
==
оператор дляaccounts
структуры. - Просто перейдите
test
к тестированию. - Передайте функцию для выполнения сравнения.
Первый простой, вы можете скопировать и вставить это, если хотите,
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,
- std::list don’t have [] operator.
- If you need [] operator then another option is std::vector.
- 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»);
}
|
|
This is supposed to be the default constructor. You don’t need the class modifier. All you need is:
|
|
I modified and I still get the same error
It might be something on the code? Or in the UnitTest cpp?
Last edited on
|
|
You can’t compare an enum with an int.
Try this:
|
|
|
|
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.