Привет, ребята, надеюсь, вы преуспеваете в своем путешествии по программированию. В предыдущем блоге я обсуждал основные вещи, такие как массивы, что такое STL, тип STL и т. д.

Сегодня я буду обсуждать еще несколько концепций STL Итак, давайте начнем.

Рекомендации по тому, что мы обсуждаем сегодня

1. Векторы

2. Инициализация векторов.

3. Методы доступа к элементам векторов

Векторы

Что такое векторы?

Векторы — это динамические массивы, размер которых можно изменять во время выполнения программы. Они похожи на массивы, но это что-то особенное, что больше всего нравится конкурентным программистам, но почему больше всего вы сейчас увидите 😉😉😉😉.

Инициализация векторов

Инициализация одномерных векторов

// To intialize the 1-D vectors
vector<datatype name> variable-name;
// Example of intialization of the 1-D vector.
vector<int> vec;
vector<string> vec;
vector<double> vec;
vector<char> vec;
vector<pair<int,int>> vec;
we can also do the intialization for all type of primitive datatypes, derived datatypes etc.

Инициализация двумерных векторов

// To intialize the 2-D vectors
vector<vector<datatype>> variable-name;

// Example of the intialization of the 2-D vector.
vector<vector<int>> vec;
vector<vector<string>> vec;
vector<vector<char>> vec;
vector<vector<double>> vec;
vector<vector<pair<int,int>>> vec; 

Точно так же мы также можем инициализировать векторы для 3-D, 4-D……n-D измерений. Давайте возьмем пример того, как инициализировать трехмерные векторы.

// To intialize the 3-D vectors
vector<vector<vector<data-type>>> variable-name;
// Example of the intialization of the 3-D vectors.
vector<vector<vector<int>>> vec;
vector<vector<vector<char>>> vec;
vector<vector<vector<string>>> vec;
vector<vector<vector<double>>> vec;
vector<vector<vector<pair<int,int>>>>

Методы доступа к элементам векторов

По обычному массиву или итеративному подходу

// How to access the elements of the vectors by the normal array method
vector<int> elementvector;
for(int i =0; i<elementvector.size();i++){
      cout<<elementvector[i];
}

// for 2-D vectors to access the elements we have
for(int i=0; i<elementvector.size();i++){
     for(int j=0; j<elementvector.size(); j++){
         cout<<elementvector[i][j];
     }
}

Используя метод итерации цикла for-each

// How to access the element of the vectors by using the for-each method
// my favourite method for approaching the elements in the vectors.
vector<int> elementsvector;
for(auto it: elementsvector){
     cout<<it<<" ";
}

// auto is the keyword in the C++ which automatically assign the datatype of the variable which is being used by the variable
// In 2-D vector accessing of the elements using the auto variable is easy take a look
vector<vector<int>> dimensionalvector;
for(auto it : dimensionalavector){
    for(auto element: it){
        cout<<element<<" ";
}
       cout<<endl;
}

// In this the 2-D loop the first variable which is it is of the vector type which is 1-D vector.
// And the second variable element is of the type int which is accessing the element from the it vector and the element variable in the above example is used to display all the elements in the 2-D vector.

С помощью итераторов

Как обсуждалось в моем предыдущем блоге, итераторы — это ссылки на элементы в контейнере.

Как инициализировать итераторы и использовать их для доступа к элементам в векторах: -

vector<int> elementvector
vector<int>::iterator it= elementvector.begin()
// This is used to point to the first element of the vector.
// How to iterate using the iterator it.
while(it!=end){
    cout<<(*it); // it is the pointer which points the element of  the vector now to access the elements of the vector we use it pointer.
}

// Another method for accessing the elements of the vectors by using the auto keyword.
for(auto it= elementvector.begin(); it!=elementvector.end();it++){
    cout<<(*it); 
}
// as the auto keyword will detect the it variable which is of type pointer and refering to the element in the vector. 

Это все для блога. Теперь в следующем блоге мы обсудим методы, используемые в векторах, и запустим набор контейнеров.

Теперь, чтобы узнать о введении STL и итераторов, вы можете проверить этот блог



Подпишитесь на меня, чтобы подписаться назад

Скоро увидимся в моем следующем блоге. А пока продолжайте писать код и продолжайте развиваться…