user3488285 user3488285 - 2 months ago 5
C++ Question

Looping vector in C++ causes invalid iterations

I have written a small program that takes inputs as string which is stored in a vector.

Looping through the vector causes many empty strings being printed before actual output.
I have copied the sample lines below.

int main(){
int totalStrings;
string inputs;
vector<string> testCases(totalStrings);
cin>>totalStrings;
while(cin>>inputs)
testCases.push_back(inputs);
for(vector<string>::iterator it=testCases.begin();it!=testCases.end();++it)
printCustom(*it);
return 0;
}


I tried printing the size of the string in the printCustom function. I had hundreds of zero printed before the actual input

Answer
vector<string> testCases(totalStrings);

This line of code has two issues:

  1. totalStrings is uninitialized and thus garbage,
  2. vector(N) creates a vector of size N default-initialized elements, as though you had called resize rather than reserve on the vector.

What you wanted was:

std::cin >> totalStrings;
std::vector<std::string> testCases;
testCases.reserve(totalStrings);