嘗試以下操作前打印:
cin>>totalStrings;
vector<string> testCases(totalStrings);
你已經初始化totalStrings(如INT)沒有一個適當的值,你用它來初始化向量。這是不好的時候!
此外,請檢查您的縮進(非常好的做法)。
一切順利。
爲了解釋進一步(請檢查代碼,如果需要的話):
在代碼中,你寫道:
int totalStrings;
string inputs;
vector<string> testCases(totalStrings);
點1: 在第一行,你有沒有初始化totalStrings到任何東西。在這種情況下,取決於計算機,矢量可以初始化爲任意可能的長度。在我的電腦,如果我做到以下幾點:
int totalStrings;
cout << totalStrings; // printing un-initialized totalStrings
string inputs;
vector<string> testCases(totalStrings);
的代碼打印零,這意味着totalStrings,通過魔法,初始化爲零。但是你的系統可能會也可能不會這樣。
點2: 現在,當您初始化一個預定義大小的向量時,您已經爲值提供了空間,但默認情況下沒有值。而且,由於您使用的是push_back方法,因此您正在放大矢量並將其添加到矢量的末尾。
最終輸出中的點1和點2的含義; 因此,當您打印時(使用for循環和迭代器),您將獲得與初始長度(由totalStrings和向量初始化定義)一樣多的零;打印完初始矢量後,它將打印您手動輸入的字符串。
請使用下面的代碼來獲得一種感覺。我希望這有幫助。
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
int totalStrings;
cout << "Please enter initial vector length: ";
cin >> totalStrings;
vector<string > testCases(totalStrings);
string inputs;
cout << "Enter the strings into the vector [Enter -1 to finish]: ";
while(true) {
cin >> inputs;
if (inputs == "-1") { break; }
testCases.push_back(inputs);
cout << "Next? ";
}
for (vector<string>::iterator it = testCases.begin(); it != testCases.end(); ++it)
cout << ' ' << it->size();
return 0;
}
你能告訴我們printCustom'的'的內容? –
停止猜測你使用的是什麼並閱讀文檔,然後將該代碼解釋給你的橡皮鴨。 –
另外,打開更多的編譯器警告。 –