I have two vectors. One char vector contains elements which each element stores a character of a paragraph (including dot . The other is a string vector whose each element should store a word created from the first vector.
Here is my code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string source = "Vectors are sequence containers representing arrays that can change in size!";
vector<char> buf(source.begin(),source.end());
vector<string> word;
size_t n = 0;
size_t l = 0;
for (size_t k = 0; k < buf.size(); k++) {
if (buf[k] == ' ' || buf[k] == '\0') {
for (size_t i = n; i < k; i++) {
word[l] = word[l] + buf[i];
}
n = k + 1;
l++;
}
}
for (size_t m = 0; m < word.size(); m++) {
cout << word[m] << endl;
}
return 0;
}
And then the system said that:
Expression: vector subscript out of range
"this project" has triggered a breakpoint
Of course, I have tried so many way to concatenate buf
elements into a single word
element( using .push_back()
, to_string()
,...) but it always caught errors. I dont try with normal array or const char*
data type since my exercise requires me to use string
and vector
only.