2

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;
}
urban
  • 5,392
  • 3
  • 19
  • 45
Bhanu
  • 21
  • 2
  • Check out https://stackoverflow.com/a/1065800/3727050 - Your array syntax is only initialising the first value from what I see... – urban Jun 25 '20 at 08:59

2 Answers2

1
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.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
0
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.

digital_hog
  • 202
  • 1
  • 11
  • Thank you. Is there any way i can assign -1 to all index of the array too.. – Bhanu Jun 25 '20 at 07:43
  • If you know NO_OF_CHARS, you could initialize it with int lastIndex[NO_OF_CHARS]={-1, -1, .....}; (NO_OF_CHARS entries in the aggregate). A more elegant way is to use a for loop and set every entry to -1. – digital_hog Jun 25 '20 at 07:45
  • i tried but they are giving different results.. NO_OF_CHARS=256 – Bhanu Jun 25 '20 at 07:48
  • The for loop may look like this: for (int i = 0; i – digital_hog Jun 25 '20 at 08:00
  • #define NO_OF_CHARS 256 int longestUniqueSubsttr(string str) { int n = str.size(); int res = 0; vector 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< – Bhanu Jun 25 '20 at 08:01
  • okay thank you.. but why does it work when i make int a[n] ={0} , then all n are assigned to 0 – Bhanu Jun 25 '20 at 08:03
  • You are in fact right, int lastIndex[NO_OF_CHARS]={-1}; will set all entries of lastIndex to -1. Sorry for the mistake. – digital_hog Jun 25 '20 at 08:17