Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.78/9: Рейтинг темы: голосов - 9, средняя оценка - 4.78
0 / 0 / 0
Регистрация: 25.05.2012
Сообщений: 32
1

Нужно дореализовать доступ по индексу в матрице

28.05.2012, 11:03. Показов 1751. Ответов 9
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
В общем, не могу доделать доступ по индексу - не знаю, как избавиться от ошибки.
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include "iostream"
#include "ctime"
#include "stdlib.h"
#include <cstdlib>
 
 
using namespace std;
 
class Matrix
{
    int m; // количество строк
    int n; // количество столбцов
    double **Matr;
public:
    Matrix(int _n, int _m);
 
    void MatrixInit(int, int);
    void random_put();
 
    Matrix operator+(Matrix );
 
    Matrix operator+(int );
    Matrix operator+(double );
 
    void operator=(int );
    void operator=(double );
 
    double operator()(int, int);
 
    void Print();
 
};
 
Matrix::Matrix(int _n, int _m)
{
    n = _n;
    m = _m;
    Matr = new double*[m];
    for(int i=0; i<m; i++)
        Matr[i]=new double[n];
}
 
void Matrix::random_put()
{
    for(int i=0; i<m; i++)
    {
        for(int j=0; j<n; j++)
        {
            cout<<"Vvedite ["<<i<<"]["<<j<<"] element: ";cin>>Matr[i][j];
        }
    }
}
 
Matrix Matrix::operator+(Matrix A)
{
    Matrix temp(A.n, A.m);
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            temp.Matr[i][j]=Matr[i][j] + A.Matr[i][j];
    return temp;
}
 
Matrix Matrix::operator+(int A)
{
    Matrix temp(n, m);
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            temp.Matr[i][j]=Matr[i][j] + A;
    return temp;
}
 
Matrix Matrix::operator+(double A)
{
    Matrix temp(n, m);
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            temp.Matr[i][j]=Matr[i][j] + A;
    return temp;
}
 
void Matrix::operator=(int A)
{
 
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            Matr[i][j]= A;
 
}
 
void Matrix::operator=(double A)
{
 
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++)
            Matr[i][j]= A;
 
}
 
double Matrix::operator()(int index, int index2)
{
    if(index >= 0 && index2 >= 0)
        if( index <= n && index2 <= m)
            return Matr[index][index2];
        else
            cout << "error index";
    else
        cout << "error index";
}
 
void Matrix::Print()
{
    for(int i=0; i<m; i++)
    {
        cout << endl;
        for(int j=0; j<n; j++)
            cout << Matr[i][j] << " ";
    }
    cout <<endl;
}
 
int main()
{
   int i, j, t, index2, index;
    cout << "Vvedite razmer matrici, i = ";
    cin >> i;
    cout << "Vvedite razmer matrici, j = ";
    cin >> j;
    Matrix Q(i,j);
    Q.random_put();
    cout << "Pervaya matrica:";
    Q.Print();
 
    Matrix W(i,j);
    W.random_put();
    cout << "Vtoraya matrica:";
    W.Print();
 
    cout << "Rezultat slozhenia matric:";
    W = Q + W;
    W.Print();
    cout << "Vvedite chislo, t = ";
    cin >> t;
    W = Q + t;
    W.Print();
 
    cout << "Vvedite pervii indeks, i = ";
    cin >> index;
    cout << "Vvedite vtoroi indeks, j = ";
    cin >> index2;
{
       if(index >= 0 && index2 >= 0)
        if( index <= i && index2 <= j)
            return Matrix.Matr[index][index2];     expected primary-expression before '.' token
        else    cout << "error index";
    else    cout << "error index";
}
}
Добавлено через 50 минут
Неужели никто не знает?)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
28.05.2012, 11:03
Ответы с готовыми решениями:

Какую коллекцию предпочесть, если нужно использовать доступ по индексу?
Друзья! Полностью вопрос звучит так: Необходимо, чтбы ответ был более или менее осознанным,...

std::vector доступ по индексу vs доступ по итератору
std::vector&lt;int&gt; tmp; int i = 0; tmp.resize(1000000); std::vector&lt;int&gt;::iterator it...

Доступ к индексу пиктограммы
При создании файла или папки непосредственно в программе надо что бы пиктограмма файла отличалась...

Инициализация List и доступ по индексу
Зная размер массива решил заранее инициализировать и раскидать данные по листу, но увы не...

9
320 / 270 / 128
Регистрация: 24.05.2012
Сообщений: 629
28.05.2012, 11:08 2
C++
1
2
3
4
5
6
7
8
class Matrix {
    //...
    double** Matr;
public:
    //...
    double* operator[ ](int m) { return Matr[m]; }
    const double* operator[ ](int m) const { return Matr[m]; }
};
0
0 / 0 / 0
Регистрация: 25.05.2012
Сообщений: 32
28.05.2012, 11:50  [ТС] 3
Не решило проблему, по-прежнему не компилится.
0
320 / 270 / 128
Регистрация: 24.05.2012
Сообщений: 629
28.05.2012, 14:24 4
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
#ifndef MATRIX_H
#define MATRIX_H
 
#   include <exception>
 
    class MatrixLine {
        friend class Matrix;
        const unsigned n;
        double* const data;
 
        MatrixLine(double*, unsigned);
        void operator=(const MatrixLine& m) { }
    public:
        double& operator[ ](unsigned) throw (std::exception);
        const double& operator[ ](unsigned) const throw (std::exception);
    };
 
    class Matrix {
        unsigned m, n;
        double* data;
    public:
        Matrix(unsigned = 1, unsigned = 1) throw (std::exception);
        Matrix(const Matrix&);
        ~Matrix();
 
        Matrix operator-() const;
        Matrix operator+(const Matrix&) const;
        Matrix operator+(const double&) const;
        Matrix operator-(const Matrix&) const;
        Matrix operator-(const double& d) const { return *this + -d; }
        Matrix operator*(const Matrix&) const;
        Matrix operator*(const double&) const;
        Matrix operator/(const Matrix&) const;
        Matrix operator/(const double& d) const { return *this * (1. / d); }
        Matrix& operator=(const Matrix&);
        Matrix& operator=(const double&);
 
        MatrixLine operator[ ](unsigned) throw (std::exception);
        const MatrixLine operator[ ](unsigned) const throw (std::exception);
    };
 
#endif
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include "Matrix.h"
 
using namespace std;
 
MatrixLine::MatrixLine(double* d, unsigned dim):
    data(d),
    n(dim)
{
}
 
double& MatrixLine::operator[ ](unsigned d2) throw (exception) {
    if (d2 < n)
        return data[d2];
    throw exception();
}
 
const double& MatrixLine::operator[ ](unsigned d2) const throw (exception) {
    if (d2 < n)
        return data[d2];
    throw exception();
}
 
 
Matrix::Matrix(unsigned d1, unsigned d2) throw (exception) {
    if (!d1 || !d2)
        throw exception();
    m = d1;
    n = d2;
    data = new double[m * n];
}
 
Matrix::Matrix(const Matrix& mx) {
    m = mx.m;
    n = mx.n;
    data = new double[m * n];
}
 
Matrix::~Matrix() {
    delete[ ] data;
}
 
Matrix Matrix::operator-() const {
    Matrix result(m, n);
    for (unsigned i = 0, j; i < m; i++)
        for (j = 0; j < n; j++)
            result.data[j * m + i] = -data[j * m + i];
    return result;
}
 
Matrix Matrix::operator+(const Matrix& mx) const {
    Matrix result(m, n);
    const unsigned m1 = (m < mx.m)? m: mx.m,
        n1 = (n < mx.n)? n: mx.n;
    for (unsigned i = 0, j; i < m1; i++)
        for (j = 0; j < n1; j++)
            result.data[j * m + i] = data[j * m + i] + mx.data[j * m + i];
    return result;
}
 
Matrix Matrix::operator+(const double& d) const {
    Matrix result(m, n);
    for (unsigned i = 0, j; i < m; i++)
        for (j = 0; j < n; j++)
            result.data[j * m + i] = data[j * m + i] + d;
    return result;
}
 
Matrix Matrix::operator-(const Matrix& mx) const {
    Matrix result(m, n);
    const unsigned m1 = (m < mx.m)? m: mx.m,
        n1 = (n < mx.n)? n: mx.n;
    for (unsigned i = 0, j; i < m1; i++)
        for (j = 0; j < n1; j++)
            result.data[j * m + i] = data[j * m + i] - mx.data[j * m + i];
    return result;
}
 
Matrix Matrix::operator*(const Matrix& mx) const {
    Matrix result(m, n);
    const unsigned m1 = (m < mx.m)? m: mx.m,
        n1 = (n < mx.n)? n: mx.n;
    for (unsigned i = 0, j; i < m1; i++)
        for (j = 0; j < n1; j++)
            result.data[j * m + i] = data[j * m + i] * mx.data[j * m + i];
    return result;
}
 
Matrix Matrix::operator*(const double& d) const {
    Matrix result(m, n);
    for (unsigned i = 0, j; i < m; i++)
        for (j = 0; j < n; j++)
            result.data[j * m + i] = data[j * m + i] * d;
    return result;
}
 
Matrix Matrix::operator/(const Matrix& mx) const {
    Matrix result(m, n);
    const unsigned m1 = (m < mx.m)? m: mx.m,
        n1 = (n < mx.n)? n: mx.n;
    for (unsigned i = 0, j; i < m1; i++)
        for (j = 0; j < n1; j++)
            result.data[j * m + i] = data[j * m + i] / mx.data[j * m + i];
    return result;
}
 
Matrix& Matrix::operator=(const Matrix& mx) {
    m = mx.m;
    n = mx.n;
    delete[ ] data;
    data = new double[m * n];
    for (unsigned i = 0, j; i < m; i++)
        for (j = 0; j < n; j++)
            data[j * m + i] = mx.data[j * m + i];
    return *this;
}
 
Matrix& Matrix::operator=(const double& d) {
    for (unsigned i = 0, j; i < m; i++)
        for (j = 0; j < n; j++)
            data[j * m + i] = d;
    return *this;
}
 
MatrixLine Matrix::operator[ ](unsigned d1) throw (exception) {
    if (d1 < m)
        return MatrixLine(data + d1 * n, n);
    throw exception();
}
 
const MatrixLine Matrix::operator[ ](unsigned d1) const throw (exception) {
    if (d1 < m)
        return MatrixLine(data + d1 * n, n);
    throw exception();
}
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
#include <conio.h>
#include <iostream>
#include "Matrix.h"
 
using namespace std;
 
void PrintMx(const Matrix& mx) {
    for (int i = 0, j; i < 2; i++) {
        for (j = 0; j < 3; j++)
            cout << mx[i][j] << ' ';
        cout << endl;
    }
}
 
void ScanMx(Matrix& mx) {
    for (int i = 0, j; i < 2; i++)
        for (j = 0; j < 3; j++)
            cin >> mx[i][j];
}
 
int main() {
    Matrix m(2, 3);
    ScanMx(m);
    PrintMx(m);
    cout << endl;
    m = 2;
    PrintMx(m);
    getch();
}
0
1181 / 894 / 94
Регистрация: 03.08.2011
Сообщений: 2,461
28.05.2012, 14:36 5
C++
1
2
3
4
double Matrix::operator()(int index, int index2)
{
   return Matr[index][index2];
}
Проводить проверку на выход за границу нужно в отдельной функции, или непосредственно в месте обращения. Иначе при наличии выхода у Вас ничего не возвращается, а возвращаемый функцией тип указывает, что она должна вернуть значение типа double.
Цитата Сообщение от Lokosios Посмотреть сообщение
return Matrix.Matr[index][index2];
И что это за обращение в main()? Зачем тут имя класса, за которым следует имя скрытых элемент данных? Да и вообще весь этот блок, который был вырезан из определения функции к чему там? Позволю себе предположить, что весь код до этого блока не Ваш.
0
0 / 0 / 0
Регистрация: 25.05.2012
Сообщений: 32
28.05.2012, 15:43  [ТС] 6
Не спорю, часть кода не моя. Но это не отменяет того, что я переделывал его?) И я хотел разобраться, в чем причина ошибки и как её решить) Причину мне указали, вестимо, а решения проблемы я так и не нашел
0
320 / 270 / 128
Регистрация: 24.05.2012
Сообщений: 629
28.05.2012, 15:47 7
Причина в том, что Вы пишете "Matrix.Matr" внутри класса, когда надо просто "Matr". Плюс еще отсутствует освобождение памяти, но на это компилятор не будет ругаться.
Стопроцентно рабочее решение я предложил в своем предыдущем сообщении.
0
1181 / 894 / 94
Регистрация: 03.08.2011
Сообщений: 2,461
28.05.2012, 15:58 8
Я не пойму, Вы хотите изменить данные? Правильно? То есть пользователь вводит номер строки, номер столбца, а затем меняет элемент по этому адресу? Тогда нужно просто возвращать ссылку на объект.

C++
1
2
3
4
double &Matrix::operator()(int index, int index2)
{
   return Matr[index][index2];
}
C++
1
2
3
4
5
6
7
    cout << "Vvedite pervii indeks, i = ";
    cin >> index;
    cout << "Vvedite vtoroi indeks, j = ";
    cin >> index2;
    
    cout << "Enter the value: ";
    cin >> W( index, index2 );
0
0 / 0 / 0
Регистрация: 25.05.2012
Сообщений: 32
28.05.2012, 16:13  [ТС] 9
Нет, пользователь вводит номер строки, затем столбца и затем на экран выводится число из этой ячейки матрицы.
0
1181 / 894 / 94
Регистрация: 03.08.2011
Сообщений: 2,461
28.05.2012, 16:17 10
Тогда всего лишь нужно написать вот так.
C++
1
2
3
4
5
6
    cout << "Vvedite pervii indeks, i = ";
    cin >> index;
    cout << "Vvedite vtoroi indeks, j = ";
    cin >> index2;
    
    cout << "Value: " << W( index, index2 );
1
28.05.2012, 16:17
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
28.05.2012, 16:17
Помогаю со студенческими работами здесь

Доступ к вектору по индексу как в Пайтоне?
Привет. Есть вектор с числами, хочу сначала его отсортировать, а потом вывести на экран первое...

Доступ к произвольному элементу последовательности по индексу
Реализуйте процедуру доступа к произвольному элементу последовательности (правильного списка,...

Доступ по индексу после передачи дека в функцию
Здравствуйте. template&lt;class P&gt; void Input(deque&lt;P&gt; *MyD, P s) { int i = 0; int size =...

[WPF] Получить доступ к элементу в ItemsControl по его индексу
Есть код: &lt;ItemsControl x:Name=&quot;mainList&quot;&gt; &lt;ItemsControl.ItemTemplate&gt; ...


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

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru