Ошибка c2678 бинарный не найден оператор

При компиляции Visual Studio выдает ошибку:
error C2678: бинарный «<«: не найден оператор, принимающий левый операнд типа «const _Ty» (или приемлемое преобразование отсутствует).
Что это значит и как ее исправить?
P.S. Если данные пояснения помогут, то вот они:
Структура Shape — прямоугольник, первые две координаты у которого (x0, y0) — левая нижняя его вершина, вторые две
(x1, y1) — правая верхняя. Вершины прямоугольника лежат в узлах целочисленной решетки.
Структура Point — точка хранит координаты точки x0, y0.
Функция PointInShape проверяет, лежит ли точка в прямоугольнике.
Функция PointInArea проверяет, лежит ли точка в каком-нибудь из прямоугольников, а также посещали ли мы ее ранее.
Вектор shapes — набор прямоугольников
Словарь used хранит информацию, посещена ли вершина point.
Словарь dist хранит расстояния до вершин от стартовой.
Во входном файле задано количество прямоугольников n и в следующих n строках заданы прямоугольники в виде
координат левой нижней и правой верхней вершин.
В последних двух строках заданы координаты стартовой и конечной вершин.
Разрешено посещать только те вершины, которые находятся хотя бы в одном из многоугольников.
Ходить можно только конем, как в шахматах (на две клетки вверх/вниз и на одну в перпендикулярном направлении).
Необходимо вывести в выходной файл расстояние length между вершинами или -1, если между ними нет пути.
Пример входных данных:
3
0 0 2 2
1 2 4 2
4 1 6 3
0 0
1 1
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <cstdlib>
#include <vector>
#include <map>
#include <fstream>
#include <queue>
using namespace std;


struct Shape {
	long x0, y0, x1, y1;
	explicit Shape(const long X0, const long Y0, const long X1, const long Y1) {
		x0 = X0;
		y0 = Y0;
		x1 = X1;
		y1 = Y1;
	}
};

struct Point {
	long x0, y0;
	explicit Point(const long X0,const long Y0) {
		x0 = X0;
		y0 = Y0;
	}
};

bool PointInShape(const Shape& shape,const Point& point) {
	if (point.x0 >= shape.x0 && point.x0 <= shape.x1 &&
		point.y0 >= shape.y0 && point.y0 <= shape.y1) return true;
	return false;
}

bool PointInArea(const vector <Shape>& sh, const map <Point, bool>& u,const Point& point) {
	bool InUsed = u.count(point);
	for (const Shape& s : sh) {
		if (PointInShape(s, point) && !InUsed) return true;
	}
	return false;
}

int main() {
	ifstream file_in("infile.txt");
	ofstream file_out("outfile.txt");
	long n;
	file_in >> n;
	long x1, y1, x2, y2;
	vector <Shape> shapes;
	map <Point, bool> used;
	map <Point, long> dist;
	for (int i = 0; i < n; ++i) {
		file_in >> x1 >> y1 >> x2 >> y2;
		shapes.push_back(Shape( x1, y1, x2, y2 ));
	}
	file_in >> x1 >> y1 >> x2 >> y2;
	const Point start(x1, y1);
	const Point end(x2, y2);
	queue <Point> points;
	points.push(start);
	dist[start] = 0;
	long length = -1;
	while (!points.empty()) {
		Point point = points.front();
		points.pop();
		for (const Point& p : {Point(point.x0+2, point.y0+1),
			Point(point.x0+2, point.y0-1),
			Point(point.x0+1, point.y0+2),
			Point(point.x0-1, point.y0-2)}) {
			if (p.x0 == end.x0 && p.y0 == end.y0) {
				length = dist[point] + 1;
				file_out << length;
				return 0;
			}
			else {
				if (PointInArea(shapes, used, p)) {
					points.push(p);
					dist[p] = dist[point] + 1;
				}
			}
		}
	}
	file_out << length;
	return 0;
}

Алгоритм идентификации.

Задание: при разработке механизма идентификации и аутентификации проверить пароль(в пароле должны чередоваться русские и латинские буквы и его длина не должна превышать 15 символов).

Решение мое:

#include "LAB4.h"
void main()
{
    setlocale(LC_ALL, "RUSSIAN");
    int choice = 0;
    while (choice != 2) {
        choice = menu();
        switch (choice) {
        case 1:
            if (check_pass())
                cout << "Пароль удовлетворяет условиям.n";
            else
                cout << "Пароль не удовлетворяет условиям!n";
            break;
        case 2:
            exit(0);
            break;
        default:
            break;
        }
    }
    return;
}

int menu()
{
    cout << "Выберите нужный пункт меню.n";
    cout << "1.Проверить парольn";
    cout << "2. Выходn";
    cout << "Ваш выбор: ";
    int ch = 0;
    cin >> ch;
    return ch;
}

bool check_pass()
{
    string passEN = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
    string passRU /*char *passEN */  = /*new char */ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
    int ctr = 0;
    cout << "Требования к паролю:n1.Пароль должен содержать 12 символов.n2.В пароле чередуются буквы и цифры.n";
    cout << "Введите пароль: ";
    string pass;
    cin >> pass;
    cout << "Длина пароля -> " << pass.length() << endl;
    int len = pass.length();        //длина пароля
    int lenEN = passEN.length();        //длина англ алфавита
    int lenRU = passRU.length();        //длина рус алфавита
    if (len <= 15)
        for (int i = 0; i < lenRU; i++) {
            if ((isalpha(passRU[i]) && isalpha(passEN[i + 1])) || (isalpha(passEN[i]) && isalpha(passRU[i + 1]))) {
                ctr = ctr + 1;
            }
            if (ctr == len)
                return true;
        }
    return false;
}

Выдает ошибку:

1>error C2678: бинарный ">>": не найден оператор, принимающий левый операнд типа "std::istream" (или приемлемое преобразование отсутствует)

Код h файла:

#include <iostream>
#include <clocale>
#include <stdio.h>
#include <string.h>

using namespace std;

int menu();
bool check_pass();

Почему ошибка вылезает и как от нее избавиться, чтобы все заработало.

Nicolas Chabanovsky's user avatar

задан 17 дек 2012 в 16:36

Антон Худайбердин's user avatar

2

operator>> не перегружен для istream и string, только для C-строк (char*). Используйте лучше getline и, если нужно, проверяйте в полученной строке наличие пробелов.

А Вы уверены, что isalpha работает для кириллицы? На самом деле, нет. Нужно использовать wstring, wchar_t и функции для работы с ними (см. заголовок cwchar). К тому же, придется получать строку wstring из wcin и уже с нею работать. Совет: для начала отработайте программу только на латинице и уже потом переходите к кириллице.

ответ дан 17 дек 2012 в 16:51

skegg's user avatar

skeggskegg

23.8k2 золотых знака37 серебряных знаков69 бронзовых знаков

1

I am using vs2012 and having the same problem. below is my sample source code.

#include "stdafx.h"
#include "iostream"
#include "list"
#include "algorithm"
#include "xutility"

using namespace std;

typedef struct Student{
   string name;
   int age;

  int operator==(list<Student>::iterator itr)
  {
    return (!strcmp(itr->name.c_str(),this->name.c_str()));
  }
}SStudent;


 int _tmain(int argc, _TCHAR* argv[])
 {
    list<SStudent> myList;
    SStudent temp1;
    temp1.age = 10;
    temp1.name = "aaaa";

    myList.push_back(temp1);

    list<SStudent>::iterator itr;
     itr = std::find(myList.begin(), myList.end(), "aaaa");

    return 0;
 }

here is the error:
Error 1 error C2678: binary ‘==’ : no operator found which takes a left-hand operand of type ‘Student’ (or there is no acceptable conversion) c:program files (x86)microsoft visual studio 11.0vcincludexutility 3186

netfeas

0 / 0 / 0

Регистрация: 27.04.2020

Сообщений: 5

1

16.05.2022, 19:16. Показов 1611. Ответов 5

Метки set, с++ (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте, пытаюсь добавить элементы в контейнер set, но выходит ошибка, не могу понять в чем проблема.
main.cpp

C++
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
#include <iostream>
#include <set>
#include "C:UsersDomDesktopZadacha2Time.h"
using namespace std;
typedef set<Time>st;
typedef set <Time>::iterator it;
 
st make_set(int n)
{
    st st;
    Time a;
    for (int i = 0; i < n; i++) {
        cin >> a;
        st.insert(a);
    }
    return st;
}
 
 
int main()
{
    st st; int n;
    cout << "Vvedite razmernost': "; cin >> n;
    st = make_set(n);
}

Time.h

C++
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
pragma once
#include <iostream>
 
using namespace std;
class Time
{
    int min, sec;
public:
    Time() { min = 0; sec = 0; };
    Time(int m, int s) { min = m; sec = s; }
    Time(const Time& t) { min = t.min; sec = t.sec; }
    ~Time() {};
    int get_min() { return min; }
    int get_sec() { return sec; }
    void set_min(int m) { min = m; }
    void set_sec(int s) { sec = s; }
    //перегруженные операции
    Time& operator=(const Time&);
    Time operator+(const Time&);
    Time operator+=(const Time&);
    Time operator/(const Time&);
    Time operator/(const int&);
    bool operator >(const Time&);
    bool operator <(const Time&);
    bool operator==(const Time&);
    bool operator!=(const Time&);
    //глобальные функции ввода-вывода
    friend istream& operator>>(istream& in, Time& t);
    friend ostream& operator<<(ostream& out, const Time& t);
};

Time.cpp

C++
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "Time.h"
 
// перегрузка операции присваивания
Time & Time::operator=(const Time & t)
{
    //проверка на самоприсваивание
    if (&t == this) return *this;
    min = t.min;
    sec = t.sec;
    return *this;
}
 
//перегрузка глобальной функции-операции ввода
istream& operator>>(istream& in, Time& t)
{
    cout << "min?"; in >> t.min;
    cout << "sec?"; in >> t.sec;
    return in;
}
//перегрузка глобальной функции-операции вывода
ostream& operator<<(ostream& out, const Time& t)
{
    return (out << t.min << " : " << t.sec);
}
 
bool Time::operator==(const Time& t)
{
    if (min == t.min && sec == t.sec)return true;
    return false;
}
 
bool Time::operator!=(const Time& t)
{
    if (min != t.min || sec != t.sec)return true;
    return false;
}
 
bool Time::operator <(const Time& t)
{
    if (min > t.min)return true;
    if (min == t.min && sec > t.sec)return true;
    return false;
    
}
 
bool Time::operator >(const Time& t)
{
    if (min > t.min)return true;
    if (min == t.min && sec > t.sec)return true;
    return false;
}
 
Time Time::operator+(const Time& t)
{
    int temp1 = min * 60 + sec;
    int temp2 = t.min * 60 + t.sec;
    Time p;
    p.min = (temp1 + temp2) / 60;
    p.sec = (temp1 + temp2) % 60;
    return p;
}
 
Time Time::operator+=(const Time& t)
{
    int temp1 = min * 60 + sec;
    int temp2 = t.min * 60 + t.sec;
    Time p;
    p.min = (temp1 + temp2) / 60;
    p.sec = (temp1 + temp2) % 60;
    return p;
}
 
//перегрузка бинарной операции деления
Time Time::operator/(const Time& t)
{
    int temp1 = min * 60 + sec;
    int temp2 = t.min * 60 + t.sec;
    Time p;
    p.min = (temp1 / temp2) / 60;
    p.sec = (temp1 / temp2) % 60;
    return p;
}
Time Time::operator/(const int& t)
{
    int temp1 = min * 60 + sec;
    Time p;
    p.min = (temp1 / t) / 60;
    p.sec = (temp1 / t) % 60;
    return p;
}



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

16.05.2022, 19:16

5

zss

Модератор

Эксперт С++

13256 / 10396 / 6214

Регистрация: 18.12.2011

Сообщений: 27,814

16.05.2022, 19:21

2

Глобальная функция, объявление в классе:

C++
1
friend bool operator<(const Time& t1,const Time& t2);
C++
1
2
3
4
5
bool operator<(const Time& t1,const Time& t2)
{
    if (t1.min < t2.min || t1.min == t2.min && t1.sec < t2.sec)return true;
    return false;
}



0



0 / 0 / 0

Регистрация: 27.04.2020

Сообщений: 5

16.05.2022, 19:28

 [ТС]

3

Не помогло, та же самая ошибка



0



TheCalligrapher

Вездепух

Эксперт CЭксперт С++

10932 / 5922 / 1621

Регистрация: 18.10.2014

Сообщений: 14,885

16.05.2022, 19:53

4

Цитата
Сообщение от netfeas
Посмотреть сообщение

C++
1
bool operator <(const Time&);

Либо

C++
1
2
bool operator <(const Time&) const;
                             ^^^^^

либо (лучше) так, как указал zss.

Цитата
Сообщение от netfeas
Посмотреть сообщение

Не помогло, та же самая ошибка

Вы что-то выдумываете. Приводите код.

Цитата
Сообщение от netfeas
Посмотреть сообщение

C++
1
2
3
4
5
6
7
8
9
10
11
12
bool Time::operator <(const Time& t)
{
    if (min > t.min)return true;
    if (min == t.min && sec > t.sec)return true;
    return false;
}
bool Time::operator >(const Time& t)
{
    if (min > t.min)return true;
    if (min == t.min && sec > t.sec)return true;
    return false;
}

Почему оба оператора определены одинаково? Для пущей замысловатости?



0



netfeas

0 / 0 / 0

Регистрация: 27.04.2020

Сообщений: 5

16.05.2022, 20:02

 [ТС]

5

TheCalligrapher,
Time.cpp

C++
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "Time.h"
 
// перегрузка операции присваивания
Time & Time::operator=(const Time & t)
{
    //проверка на самоприсваивание
    if (&t == this) return *this;
    min = t.min;
    sec = t.sec;
    return *this;
}
 
//перегрузка глобальной функции-операции ввода
istream& operator>>(istream& in, Time& t)
{
    cout << "min?"; in >> t.min;
    cout << "sec?"; in >> t.sec;
    return in;
}
//перегрузка глобальной функции-операции вывода
ostream& operator<<(ostream& out, const Time& t)
{
    return (out << t.min << " : " << t.sec);
}
 
bool Time::operator==(const Time& t)
{
    if (min == t.min && sec == t.sec)return true;
    return false;
}
 
bool Time::operator!=(const Time& t)
{
    if (min != t.min || sec != t.sec)return true;
    return false;
}
 
bool operator<(const Time& t1, const Time& t2)
{
    if (t1.min < t2.min || t1.min == t2.min && t1.sec < t2.sec)return true;
    return false;
}
 
bool Time::operator >(const Time& t)
{
    if (min < t.min)return true;
    if (min == t.min && sec < t.sec)return true;
    return false;
}
 
Time Time::operator+(const Time& t)
{
    int temp1 = min * 60 + sec;
    int temp2 = t.min * 60 + t.sec;
    Time p;
    p.min = (temp1 + temp2) / 60;
    p.sec = (temp1 + temp2) % 60;
    return p;
}
 
Time Time::operator+=(const Time& t)
{
    int temp1 = min * 60 + sec;
    int temp2 = t.min * 60 + t.sec;
    Time p;
    p.min = (temp1 + temp2) / 60;
    p.sec = (temp1 + temp2) % 60;
    return p;
}
 
//перегрузка бинарной операции деления
Time Time::operator/(const Time& t)
{
    int temp1 = min * 60 + sec;
    int temp2 = t.min * 60 + t.sec;
    Time p;
    p.min = (temp1 / temp2) / 60;
    p.sec = (temp1 / temp2) % 60;
    return p;
}
Time Time::operator/(const int& t)
{
    int temp1 = min * 60 + sec;
    Time p;
    p.min = (temp1 / t) / 60;
    p.sec = (temp1 / t) % 60;
    return p;
}

Time.h

C++
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
#pragma once
#include <iostream>
 
using namespace std;
class Time
{
    int min, sec;
public:
    Time() { min = 0; sec = 0; };
    Time(int m, int s) { min = m; sec = s; }
    Time(const Time& t) { min = t.min; sec = t.sec; }
    ~Time() {};
    int get_min() { return min; }
    int get_sec() { return sec; }
    void set_min(int m) { min = m; }
    void set_sec(int s) { sec = s; }
    //перегруженные операции
    Time& operator=(const Time&);
    Time operator+(const Time&);
    Time operator+=(const Time&);
    Time operator/(const Time&);
    Time operator/(const int&);
    bool operator >(const Time&);
    friend bool operator<(const Time& t1, const Time& t2);
    bool operator==(const Time&);
    bool operator!=(const Time&);
    //глобальные функции ввода-вывода
    friend istream& operator>>(istream& in, Time& t);
    friend ostream& operator<<(ostream& out, const Time& t);
};



0



Вездепух

Эксперт CЭксперт С++

10932 / 5922 / 1621

Регистрация: 18.10.2014

Сообщений: 14,885

16.05.2022, 21:01

6

Цитата
Сообщение от netfeas
Посмотреть сообщение

Time.cpp

И? Теперь все прекрасно компилируется без проблем. Вы же нам рассказываете какие-то странные истории про

Цитата
Сообщение от netfeas
Посмотреть сообщение

Не помогло, та же самая ошибка



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

16.05.2022, 21:01

Помогаю со студенческими работами здесь

Error C2678: бинарный «<<«: не найден оператор, принимающий левый операнд типа «std::ifstream»
Собственно, текст ошибки приведен в названии темы. Сам код:
#include &quot;stdafx.h&quot;
#include…

Бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::istream»
Подскажите, пожалуйста, как решить проблему. Хочу перегрузить оператор ввода, но никак не пойму, в…

Исправить ошибку:error C2678: бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::istream»
Скажите пожалуйста, как исправить
error C2678: бинарный &quot;&gt;&gt;&quot;: не найден оператор, принимающий…

error C2678: бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::basic_istream<_Elem,_Traits>»
Нужно из файла скачать информацию в объект. Почему у меня не получается?
#include &lt;vector&gt;…

бинарный «/»: не найден оператор, принимающий правый операнд типа «const char8_t *»
void CConfig::Load(size_t index)
{

json j;

if (std::ifstream in{ Path / (const…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2678

Compiler Error C2678

11/04/2016

C2678

C2678

1f0a4e26-b429-44f5-9f94-cb66441220c8

Compiler Error C2678

binary ‘operator’ : no operator defined which takes a left-hand operand of type ‘type’ (or there is no acceptable conversion)

To use the operator, you must overload it for the specified type or define a conversion to a type for which the operator is defined.

C2678 can occur when the left-hand operand is const-qualified but the operator is defined to take a non-const argument.

Examples

The following sample generates C2678 and shows how to fix it:

// C2678a.cpp
// Compile by using: cl /EHsc /W4 C2678a.cpp
struct Combo {
   int number;
   char letter;
};

inline Combo& operator+=(Combo& lhs, int rhs) {
   lhs.number += rhs;
   return lhs;
}

int main() {
   Combo const combo1{ 42, 'X' };
   Combo combo2{ 13, 'Z' };

   combo1 += 6; // C2678
   combo2 += 9; // OK - operator+= matches non-const Combo
}

C2678 can also occur if you do not pin a native member before calling a member function on it.

The following sample generates C2678 and shows how to fix it.

// C2678.cpp
// compile with: /clr /c
struct S { int _a; };

ref class C {
public:
   void M( S param ) {
      test = param;   // C2678

      // OK
      pin_ptr<S> ptest = &test;
      *ptest = param;
   }
   S test;
};

Понравилась статья? Поделить с друзьями:
  • Ошибка c2589 недопустимая лексема справа от
  • Ошибка c257 00 форд фокус 3
  • Ошибка c2440 невозможно преобразовать int в int
  • Ошибка c2440 инициализация невозможно преобразовать
  • Ошибка c240201 kia какой электромотор