user3488285 user3488285 - 1 year ago 75
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);
for(vector<string>::iterator it=testCases.begin();it!=testCases.end();++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 Source
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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download