Вектори

 Што е вектор во C ++?

Векторите во C ++ се динамички низи што се користат за складирање на податоци. За разлика од низите, кои се користат за складирање на последователни податоци и имаат статична природа, векторите обезбедуваат поголема флексибилност на програмата - можат автоматски да ја менуваат големината кога некој елемент се вметнува или брише.

Синтакса

vector< object_type > variable_name;

Задолжително е да се одреди типот и името на променливата. Пример vector <int > a;
За да може да користиме вектор, потребно е да вклучиме со директивата  #include <vector>
Пристап до елементите на вектор e слично како кај низите. Со a[3] пристапуваме до членот со реден број 3 

Методи 
push_back                    - додавање елемент на крај на вектор      
a.push_back(13);
ime_na_ vector .size    - одредување големина на вектор / број на елементи    
vector < int > b={10,20,30,40,50};
cout << "Vektorot ima " << b.size() << " elemenati" << endl;
ime_na_ vector .front - прв елемент на вектор 
vector < int > grupa={"Mira","Pero","Goran","Natasa"};
cout << "Prv vo grupata e " << grupa.front() << endl; 
output: Mira
ime_na_ vector .back - пoследен елемент на вектор 
vector < int > grupa={"Mira","Pero","Goran","Natasa"};
cout << "Posleden vo grupata e " << grupa.back() << endl; 
output: Natasa
ime_na_ vector .pop_back - бришење на последниот елемент во векторот 
vector < double > temperature={23.2 , 25.8 , 11, 15.3, 17};
temperature.pop_back(); 
output:23.2, 25.8, 11, 15.3

ime_na_ vector .erase бришење на елемент на одредена позиција во векторот 

vector < int > c={2,3,4};
c.erase(c.begin() + 1);                 //go brise elementot na pozicija 1 vo vektorot

ime_na_ vector .clear - бришење на сите елементи

vector < int > c={2,3,4};
c.clear();//brisenje na site elementi vo vektorot, posle ova toj e prazen

Печатење на елементите на вектор
#include <iostream>
#include < vector >
using namespace std;
int main() {
vector < int > broevi={1,2,3,4,5};
for(int i = 0; i < broevi.size(); i++)
{
cout << broevi[i] << " ";
}
cout << endl;}

​Output: 1 2 3 4 5

Сортирање на елементи 
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> a={4,2,7,5,9};
sort(a.begin(),a.end());
//Ispis
for(int i = 0; i<a.size(); i++)
        cout<<a[i];
}
Output  24579

#include <iostream>
#include <vector>
using namespace std;
int main()
{ vector <int> v;
 v.push_back(3); v.push_back(5);
 v.push_back(7);
 for(int i=10;i<14;i++)
 v.push_back(i);
 v[0]--;
 v[5]=-200;
 for(unsigned i=0;i<v.size();i++)
 cout << v[i] << ' ';
 cout << endl;
 return 0;
Output:   2 5 7 10 11 -200 13

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{ vector <string> vs;
 vs.push_back("jas"); vs.push_back("sakam");
 vs.push_back("programiranje");
 for(unsigned i=0;i<vs.size();i++)
 cout << vs[i] << ' ';
 cout << endl;
 vector < vector<int> > matrica;
 for(int i=0;i<5;i++)
 {
 vector <int> v;
 matrica.push_back(v);
 for (int j=0;j<=i;j++)
 matrica[i].push_back(j);
 }
 for(unsigned i=0;i<matrica.size();i++)
 {
 for(unsigned j=0;j<matrica[i].size();j++)
 cout << matrica[i][j] << ' ';
 cout << endl;
 }
 return 0;
Output: 
jas sakam programiranje 
0 1 
0 1 2 
0 1 2 3 
0 1 2 3 4

Iterators An iterator allows you to access the data elements stored within the C++ vector. It is an object that functions as a pointer.

  1. begin() –Returns an iterator pointing to the first element in the vector
    end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector
    rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
    rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
    cbegin() – Returns a constant iterator pointing to the first element in the vector.
    cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector.
    crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element
    crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end) 
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> vec1;   
    for (int i = 1; i <= 10; i++)
        vec1.push_back(i);    
    cout << "Understanding begin() and end() function: " << endl;
    //for (auto i = vec1.begin(); i != vec1.end(); ++i)
    //    cout << *i << " ";
   for ( int i = 0; i < vec1.size(); ++i) cout << vec1 [i];
return 0;
}

iterators




#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
    vector<int> ar = { 1, 2, 3, 4, 5 };
      
    // Declaring iterator to a vector
    vector<int>::iterator ptr;
      
    // Displaying vector elements using begin() and end()
    cout << "The vector elements are : ";
    for (ptr = ar.begin(); ptr < ar.end(); ptr++)
        cout << *ptr << " ";
          return 0;    

}
Output: The vector elements are : 1 2 3 4 5


#include <iostream>
#include <vector>
using namespace std;

int main()
{ vector <int> v;
for(unsigned i=0;i<15;i++)
v.push_back(i);
vector<int>::iterator it;
for(it=v.begin(); it!=v.end();it++)
cout << *it << ' ';
cout << endl;
return 0;
}
Output
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14


Capacity

size() – Returns the number of elements in the vector.
max_size() – Returns the maximum number of elements that the vector can hold.
capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.
resize(n) – Resizes the container so that it contains ‘n’ elements.
empty() – Returns whether the container is empty.
shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity.
reserve() – Requests that the vector capacity be at least enough to contain n elements.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> vec1;    
    for (int i = 1; i <= 10; i++)
        vec1.push_back(i);    
    cout << "Size of our vector: " << vec1.size();
    cout << "\nCapacity of our vector: " << vec1.capacity();
    cout << "\nMax_Size of our vector: " << vec1.max_size();    
    // resizes the vector size to 4
    vec1.resize(4);    
    // prints the vector size after resize()
    cout << "\nSize of our vector after resize: " << vec1.size();    
    // checks if the vector is empty or not
    if (vec1.empty() == false)
        cout << "\nVector is not empty";
    else
        cout << "\nVector is empty";
    return 0;
}

Output: ????

// resizing of the vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
// 5 elements are inserted in the vector
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
cout << "Contents of vector before resizing:" << endl;

// displaying the contents of the vector before resizing
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;

// vector is resized
vec.resize(4);
cout << "Contents of vector after resizing:" << endl;

// displaying the contents of the vector after resizing
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
return 0;
}
Output 
Contents of the vector before resizing: 1 2 3 4 5
Contents of the vector after resizing: 1 2 3 4


Modifiers:

    assign() – It assigns new value to the vector elements by replacing old ones
    push_back() – It push the elements into a vector from the back
    pop_back() – It is used to pop or remove elements from a vector from the back.
    insert() – It inserts new elements before the element at the specified position
    erase() – It is used to remove elements from a container from the specified position or range.
    swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ.
    clear() – It is used to remove all the elements of the vector container
    emplace() – It extends the container by inserting new element at position
    emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector
    // Modifiers in vector
    #include <iostream> //#include <bits/stdc++.h>
    #include <vector>
    using namespace std;
    int main()
    {
        // Assign vector
        vector<int> vec;
        // fill the array with 12 seven times
        vec.assign(7, 12);
        cout << "The vector elements are: ";
        for (int i = 0; i < 7; i++)
            cout << vec[i] << " ";    
        // inserts 24 to the last position
        vec.push_back(24);
        int s = vec.size();
        cout << "\nThe last element is: " << vec[s - 1];  
         // prints the vector
        cout << "\nThe vector elements after push back are: ";
        for (int i = 0; i < vec.size(); i++)
        cout << vec[i] << " ";    
        // removes last element
        vec.pop_back();    
        // prints the vector
        cout << "\nThe vector elements after pop_back are: ";
        for (int i = 0; i < vec.size(); i++)
            cout << vec[i] << " ";    
        // inserts 10 at the beginning
        vec.insert(vec.begin(), 10);
        cout << "\nThe first element after insert command is: " << vec[0];    
        // removes the first element
        vec.erase(vec.begin());
        cout << "\nThe first element after erase command is: " << vec[0];    
        // inserts at the beginning
        vec.emplace(vec.begin(), 5);
        cout << "\nThe first element emplace is: " << vec[0];    
        // Inserts 20 at the end
        vec.emplace_back(20);
        s = vec.size();
        cout << "\nThe last element after emplace_back is: " << vec[s - 1];    
        // erases the vector
        vec.clear();
        cout << "\nVector size after clear(): " << vec.size();    
        // two vector to perform swap
        vector<int> obj1, obj2;
        obj1.push_back(2);
        obj1.push_back(4);
        obj2.push_back(6);
        obj2.push_back(8);    
        cout << "\n\nVector 1: ";
        for (int i = 0; i < obj1.size(); i++)
            cout << obj1[i] << " ";    
        cout << "\nVector 2: ";
        for (int i = 0; i < obj2.size(); i++)
            cout << obj2[i] << " ";    
        // Swaps obj1 and obj2
        obj1.swap(obj2);
        cout << "\nAfter Swap nVector 1: ";
        for (int i = 0; i < obj1.size(); i++)
            cout << obj1[i] << " ";
        cout << "\nVector 2: ";
        for (int i = 0; i < obj2.size(); i++)
            cout << obj2[i] << " ";
    }

    Output:


      

No comments: