【发布时间】:2020-12-06 02:43:31
【问题描述】:
我正在尝试编写一些代码,通过 outisde 函数 digitSep() 获取数字的每个数字,并将其放入向量中,在本例中为 vector<int> digits;。
知道为什么我不能在 for 循环中使用 cout << digits[i] 或 cout << digits.at(i) 吗?
std::vector<int> digitSep(int d) {
vector<int> digits;
int right_digit; //declare rightmost digit
while (d > 0) {
right_digit = d % 10; //gives us rightmost digit (i.e. 107,623 would give us '3')
d = (d - right_digit) / 10; //chops out the rightmost digit, giving us a new number
digits.push_back(right_digit);
}
return digits; ///returns us a vector of digits
}
int main() {
//inputs
int n;
cin >> n;
vector<int> digitSep(n); //call the function here with user input n above
for (int i = 0; i < digitSep.size(); i++) {
cout << digits[i] << endl; ////This is the line that won't work for some reason
}
return 0;
}
【问题讨论】:
-
在
main中,没有名为digits的变量。此外,您定义了一个名为digitSep的函数,但您从未真正调用它。注释说“调用函数...”,但注释所在的行实际上并没有调用任何函数(除非您计算向量的构造函数)。
标签: c++ function vector int return