how is int lastIndex[NO_OF_CHARS]={-1}; different from vector<int> lastIndex(NO_OF_CHARS, -1);?

Viewed 192

how is the contents of

int lastIndex[NO_OF_CHARS]={-1};  

different from the contents of

vector<int> lastIndex(NO_OF_CHARS, -1); 

?

How I use it (copied from comments on @digital_hog's answer):

#define NO_OF_CHARS 256 

int longestUniqueSubsttr(string str) { 
  int n = str.size(); 
  int res = 0; 
  vector<int> lastIndex(NO_OF_CHARS,-1); // i want to replace this with array 
  
  int i = 0; 
  for (int j = 0; j < n; j++) { 
    i = max(i, lastIndex[str[j]] + 1); 
    res = max(res, j - i + 1); lastIndex[str[j]] = j; 
  } 
  return res; 
} 

int main() { 
  int t;
  cin>>t;
  while(t--) {
    string s="";
    cin>>s;
    cout<<longestUniqueSubsttr(s)<<endl;
  } 
  return 0;
}
2 Answers
int lastIndex[NO_OF_CHARS]={-1};  

declares a static array of NO_OF_CHARS int's where the first elements will be copied from the brace enclosed intializer list { -1 } and all other elements will be default-initialized (to 0 in this case). So you end up with an array [-1, 0, ..., 0]

vector<int> lastIndex(NO_OF_CHARS, -1); 

initializes a std::vector<int> (a dynamic array, if you want) with NO_OF_CHARS copies of the second parameter, e.g. NO_OF_CHARS times -1.

vector<int> lastIndex(NO_OF_CHARS, -1);

will make lastIndex look like {-1, -1, -1 ... } (NO_OF_CHARS times).

The normal static array will do the same, the difference is in the way the arrays are allocated.

Related