Using stack from standard template library

14,463

If we define the efficiency in terms of how many basic operations methods do, I believe that there is no difference between these two methods. As you may know the implementation of the std::string is based on the simple array of characters (just like std::vector) meaning that the characters are stored as continuous chunk of the memory. This allows accessing any element in a valid range in a constant number of operations (O(1)). So the retrieval of ith character str[i] requires O(1) operations just like accessing an entry of the array. Similarly, in the second method you use iterators, which are, roughly speaking, pointers to the location in the array in this context. So accessing their content *itr and moving them further by one position itr++ is of the same efficiency as moving the pointer along the array and retrieving its content.

So again, the key idea is that characters in std::string are stored in the continuous array, which gives it such capabilities. You may want to compare its implementation with std::map where the underlying implementation is a red-black tree, which, of course, is not an array. And so the [] operator works in logarithmic time (in contrast to constant in std::string).

EDIT:

As was mentioned in the comment, cout output is relatively costly (but still O(1)). So if you want to check 'real' efficiency, you have to remove output or call std::ios_base::sync_with_stdio(false); when the programs starts in order to boost the speed of cout.

Share:
14,463
KapilSantore
Author by

KapilSantore

Updated on June 14, 2022

Comments

  • KapilSantore
    KapilSantore about 2 years

    I just code a small program to transfer a character from a string onto the stack and print it's top value. They are just simple codes but with different concept,I would like to ask which one of the code is more efficient and why?

    1st code

    #include<string>
    #include<iostream>
    #include<stack>
    using namespace std;
    int main(){
       string str ;
       stack<char> s;
       cin >> str ;
       for(int i=0;i<str.size();i++){
           cout << str[i] << "\n";
           s.push(str[i]);
           cout << "Top of the stack " << s.top() << endl;}
     cout << "\n" << endl;
     return 0;}
    

    2nd code Using Iterator

    #include<string>
    #include<iostream>
    #include<stack>
    using namespace std;
    int main(){
       string str ;
       stack<char> s;
       cin >> str ;
       for(string::iterator itr = str.begin();itr!=str.end();itr++){
                 cout << *itr << "\n";
                 s.push(*itr);
                 cout << "Top of the stack " << s.top() << endl;}
     cout << "\n" << endl;
     return 0;}
    

    They are just two simple codes I just want to know which is more efficient way ??