C++ STL interview questions

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?(except when erased member is first or last member of container)
Q) What is the difference between capacity and size in vector container in STL?
Q) If initially size allocated to vector is 10. What would be the capacity of the vector? Will it be doubled?
Q) Write a program to demonstrate vector's algorithms ?
Q) Write a program to demonstrate map and multi map's algorithms?
Q) Write a program to demonstrate set and multi set's operations ?
Q) What is the return type of find algorithm in STL container?
Q) Write a program to find the  first match of pattern in given strings and its position? Use vector of strings?
Q) Write a program to find all matches of pattern in given strings and its position? Use vector of strings?
Q) What is the difference between array an vector?
Q) What is the difference between vector, list, set and map?
Q) Why vectors are thread safe?

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?
Invalidation  in vector means pointing out side of range of vector or pointing to altogether different value.
Insertion consequence in a vector:
i)All iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated.
ii)Erase consequences in vector: 
Every iterator and reference after the point of erase is invalidated.
iii)Resize effect in vector:
As per insertion and erase.
 example code of vector invalidation in c++ STL vector:
#include<iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
    int arr[] = { 10, 20, 30 };

    std::vector<int> vec(arr, arr + 3);
    // vector contains 1, 2, 3
        //size 3 and capasity 4

    std::vector<int>::iterator i = vec.begin();
    cout <<"*i="<< *i << endl; // prints 10
    int &ref = *i;
    cout <<"ref="<<ref << endl; // prints 10

    vec.resize(5, 100);
//vector now contains 1, 2, 3, 100, 100
//now capasity is 8 > size 5

    // WRONG! might work, crash or invalid result
    cout <<"*i=="<< *i << endl; // prints 0

    // WRONG! invalid reference
    cout <<"ref=="<<ref << endl; // prints 0

   return 0;
}

No comments:

Post a Comment