При компиляции 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();
Почему ошибка вылезает и как от нее избавиться, чтобы все заработало.
задан 17 дек 2012 в 16:36
2
operator>> не перегружен для istream и string, только для C-строк (char*). Используйте лучше getline и, если нужно, проверяйте в полученной строке наличие пробелов.
А Вы уверены, что isalpha работает для кириллицы? На самом деле, нет. Нужно использовать wstring, wchar_t и функции для работы с ними (см. заголовок cwchar). К тому же, придется получать строку wstring из wcin и уже с нею работать. Совет: для начала отработайте программу только на латинице и уже потом переходите к кириллице.
ответ дан 17 дек 2012 в 16:51
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, но выходит ошибка, не могу понять в чем проблема.
Time.h
Time.cpp
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 |
|||||||
Глобальная функция, объявление в классе:
0 |
0 / 0 / 0 Регистрация: 27.04.2020 Сообщений: 5 |
|
16.05.2022, 19:28 [ТС] |
3 |
Не помогло, та же самая ошибка
0 |
TheCalligrapher Вездепух 10932 / 5922 / 1621 Регистрация: 18.10.2014 Сообщений: 14,885 |
||||||||||||
16.05.2022, 19:53 |
4 |
|||||||||||
Либо
либо (лучше) так, как указал zss.
Не помогло, та же самая ошибка Вы что-то выдумываете. Приводите код. —
Почему оба оператора определены одинаково? Для пущей замысловатости?
0 |
netfeas 0 / 0 / 0 Регистрация: 27.04.2020 Сообщений: 5 |
||||||||
16.05.2022, 20:02 [ТС] |
5 |
|||||||
TheCalligrapher,
Time.h
0 |
Вездепух 10932 / 5922 / 1621 Регистрация: 18.10.2014 Сообщений: 14,885 |
|
16.05.2022, 21:01 |
6 |
Time.cpp И? Теперь все прекрасно компилируется без проблем. Вы же нам рассказываете какие-то странные истории про
Не помогло, та же самая ошибка
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
16.05.2022, 21:01 |
Помогаю со студенческими работами здесь Error C2678: бинарный «<<«: не найден оператор, принимающий левый операнд типа «std::ifstream»
Исправить ошибку:error C2678: бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::istream» error C2678: бинарный «>>»: не найден оператор, принимающий левый операнд типа «std::basic_istream<_Elem,_Traits>» бинарный «/»: не найден оператор, принимающий правый операнд типа «const char8_t *» 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; };