-2

Why are we able to compare vector element with string element without initializing the vector? How does it work?

#include <bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin>>t;
    while(t--) {
        string x; cin>>x;
        vector<char> a;
        for(int i=0;i<x.length();i++) {
            int f=0;
            for(int j=0;j<a.size();j++) {
                if(a[j]==x.at(i)) {
                    f=1;
                    break;
                }
            }
            if(f==0)
                a.push_back(x.at(i));
        }
        if(a.size()==2)
           cout<<"YES\n";
        else 
           cout<<"NO\n";
    }
    return 0;
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
D. Gaira
  • 1
  • 1
  • `vector` is initialized here. – user7860670 May 26 '18 at 11:18
  • Your vector is initialised and populated before its elements are referenced, why do you think it is not? – Killzone Kid May 26 '18 at 11:21
  • Please see these questions about [`bist/stdc++`](https://stackoverflow.com/q/31816095/1782465) and [`using namespace std;`](https://stackoverflow.com/q/1452721/1782465). Also, it's not clear why you think `a` is not initialised; can you elaborate? – Angew is no longer proud of SO May 26 '18 at 11:29
  • It is declared at vector a; But I do not know where it is initialized in the code and if it is declared then how can we compare it with the string ''x'' as it is in a[j]==x.at(i) Thank you for the help! – D. Gaira May 26 '18 at 11:44

1 Answers1

1

The definition vector<char> a; initialises a to be an empty vector. As such, its size is 0.

During the first iteration of the outer (i) loop, the inner loop for(int j=0;j<a.size();j++) { is therefore never executed and no a[j] is evaluated. Code simply follows straight to the if(f==0) check, and based on that, adds something to the vector a. Future iterations of the outer loop threfore work with a non-empty a and can look into it.

You could easily observe this yourself by stepping through the program in a debugger, to exactly see which way control flows through the code.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455