Evgenii Legotckoi
Evgenii LegotckoiDec. 23, 2015, 12:07 p.m.

Qt/C++ - Lesson 037. The two-dimensional array using QVector

Class QVector relates to a container class, and provides access to the items on the index, as well as a number of additional methods for ease of operation.

QVector instance of the class is essentially a one-dimensional array of objects. If you want to set as a vector of two-dimensional array, you can create an instance of a QVector , which will contain other instances QVector .

One-Dimensional array using QVector

For starters keep in Vector-dimensional array of type int:

QVector <int> myVector;

int massive[4] = {1, 2, 3, 4};

for(int i = 0; i < 4; i++)
{
    myVector.push_back(massive[i]);
    qDebug() << "Value " << i << ": " << myVector.value(i);
}

And look at the output qDebug() :

Value  0 :  1
Value  1 :  2
Value  2 :  3
Value  3 :  4

The two-dimensional array in QVector

Now put in a two-dimensional vector array of int:

QVector <QVector <int> > myVector;

int massive[4][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} };

for(int i = 0; i < 4; i++)
{
    QVector<int> tempVector;

    for(int j = 0; j < 4; j++)
    {
        tempVector.push_back(massive[i][j]);
        qDebug() << "Value " << j << ": " << tempVector.value(j);
    }
    myVector.push_back(tempVector);
    qDebug() << "myVector " << i << ": " << myVector.value(i);
}

And look at the output qDebug() :

Value  0 :  1
Value  1 :  2
Value  2 :  3
Value  3 :  4
myVector  0 :  QVector(1, 2, 3, 4)
Value  0 :  5
Value  1 :  6
Value  2 :  7
Value  3 :  8
myVector  1 :  QVector(5, 6, 7, 8)
Value  0 :  9
Value  1 :  10
Value  2 :  11
Value  3 :  12
myVector  2 :  QVector(9, 10, 11, 12)
Value  0 :  13
Value  1 :  14
Value  2 :  15
Value  3 :  16
myVector  3 :  QVector(13, 14, 15, 16)

An array of two-dimensional arrays using QVector

And if you want to keep all of two-dimensional arrays again in the vector, it can be done as follows:

QVector <QVector <QVector <int> > > myVector;

int massive[4][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} };

QVector <QVector <int> > matrix;

for(int i = 0; i < 4; i++)
{
    QVector<int> tempVector;

    for(int j = 0; j < 4; j++)
    {
        tempVector.push_back(massive[i][j]);
        qDebug() << "Value " << j << ": " << tempVector.value(j);
    }
    matrix.push_back(tempVector);
    qDebug() << "matrix row " << i << ": " << matrix.value(i);
}

myVector.push_back(matrix);

qDebug() << "myVector: " << myVector.value(0);

And look at the output qDebug() :

Value  0 :  1
Value  1 :  2
Value  2 :  3
Value  3 :  4
matrix row  0 :  QVector(1, 2, 3, 4)
Value  0 :  5
Value  1 :  6
Value  2 :  7
Value  3 :  8
matrix row  1 :  QVector(5, 6, 7, 8)
Value  0 :  9
Value  1 :  10
Value  2 :  11
Value  3 :  12
matrix row  2 :  QVector(9, 10, 11, 12)
Value  0 :  13
Value  1 :  14
Value  2 :  15
Value  3 :  16
matrix row  3 :  QVector(13, 14, 15, 16)
myVector:  QVector(QVector(1, 2, 3, 4), QVector(5, 6, 7, 8), QVector(9, 10, 11, 12), QVector(13, 14, 15, 16))

Conclusion

And finally, another way to work with vectors and arrays on the example of two matrices. which is somewhat different from the above the given methods. In this case, a matrix or two-dimensional array will contain one QVector . In turn, vector QVector > will contain a list of all matrices.

QVector <QVector <int *> > matrixList;
QVector <int *> matrix1;
QVector <int *> matrix2;

int massive1[2][4] = { {1,2,3,4}, {5,6,7,8} };
int massive2[2][4] = { {9,10,11,12}, {13,14,15,16} };

qDebug() << "Matrix 1";
for(int i = 0; i < 2; i++)
{
    matrix1.push_back(massive1[i]);
    for(int j = 0; j < 4; j++)
    {
        qDebug() << "[" << i << "]" << "[" << j << "]" << matrix1.value(i)[j];
    }
}

qDebug() << "Matrix 2";
for(int i = 0; i < 2; i++)
{
    matrix2.push_back(massive2[i]);
    for(int j = 0; j < 4; j++)
    {
        qDebug() << "[" << i << "]" << "[" << j << "]" << matrix2.value(i)[j];
    }
}

matrixList.push_back(matrix1);
matrixList.push_back(matrix2);

qDebug() << "Matrix 1 from matrixList";
for(int i = 0; i < 2; i++)
{
    for(int j = 0; j < 4; j++)
    {
        qDebug() << "[" << i << "]" << "[" << j << "]" << matrixList.value(0).value(i)[j];
    }
}

qDebug() << "Matrix 2 from matrixList";
for(int i = 0; i < 2; i++)
{
    for(int j = 0; j < 4; j++)
    {
        qDebug() << "[" << i << "]" << "[" << j << "]" << matrixList.value(1).value(i)[j];
    }
}

And look at the output qDebug() :

Matrix 1
[ 0 ] [ 0 ] 1
[ 0 ] [ 1 ] 2
[ 0 ] [ 2 ] 3
[ 0 ] [ 3 ] 4
[ 1 ] [ 0 ] 5
[ 1 ] [ 1 ] 6
[ 1 ] [ 2 ] 7
[ 1 ] [ 3 ] 8
Matrix 2
[ 0 ] [ 0 ] 9
[ 0 ] [ 1 ] 10
[ 0 ] [ 2 ] 11
[ 0 ] [ 3 ] 12
[ 1 ] [ 0 ] 13
[ 1 ] [ 1 ] 14
[ 1 ] [ 2 ] 15
[ 1 ] [ 3 ] 16
Matrix 1 from matrixList
[ 0 ] [ 0 ] 1
[ 0 ] [ 1 ] 2
[ 0 ] [ 2 ] 3
[ 0 ] [ 3 ] 4
[ 1 ] [ 0 ] 5
[ 1 ] [ 1 ] 6
[ 1 ] [ 2 ] 7
[ 1 ] [ 3 ] 8
Matrix 2 from matrixList
[ 0 ] [ 0 ] 9
[ 0 ] [ 1 ] 10
[ 0 ] [ 2 ] 11
[ 0 ] [ 3 ] 12
[ 1 ] [ 0 ] 13
[ 1 ] [ 1 ] 14
[ 1 ] [ 2 ] 15
[ 1 ] [ 3 ] 16
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

М
  • Nov. 3, 2017, 8:51 a.m.

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

 QVector<double>*Open1=   new QVector<double>;
 Open1->append(5); Open1->append(6);
При этом не работает так Open1[0]=7; Также при попытке вывода Open1[0] выдает ошибку. Скажите пожалуйста, где у меня ошибка?
Evgenii Legotckoi
  • Nov. 4, 2017, 6:20 a.m.

Выделили память в куче. Обращаться к элементам нужно так.

Open1->at(0);
Open1->at(1);
М
  • Nov. 7, 2017, 2:35 a.m.
Open1->at(5); Open1->at(6); Сделал так, при запуске вырубается скрипт.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Дмитрий

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
Дмитрий

C++ - Тест 003. Условия и циклы

  • Result:92points,
  • Rating points8
d
  • dsfs
  • April 26, 2024, 4:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
George13May 7, 2024, 12:27 a.m.
добавить qlineseries в функции в функции: "GPlotter::addSeries(QString title, QVector &arr)" я вызываю метод setChart(...), я в конструктор передал адрес на QChartView элемент
BlinCT
BlinCTMay 5, 2024, 5:46 a.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
PS
Peter SonMay 3, 2024, 5:57 p.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 2, 2024, 2:07 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 4:22 a.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks