简体   繁体   English

如何计算来自外部 function 的向量?

[英]How to cout a vector from an outside function?

I am trying to write some code where I take each digit of a number, via an outisde function digitSep(), and place it into a vector, in this case vector<int> digits;我正在尝试编写一些代码,通过outisde function digitSep() 获取数字的每个数字,并将其放入向量中,在本例中为vector<int> digits; . .

Any idea why I cannot cout << digits[i] or cout << digits.at(i) in a for loop?知道为什么我不能在 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;
}

This line:这一行:

vector<int> digitSep(n);

doesn't call the function called digitSep .不调用 function 称为digitSep You need to do:你需要做:

vector<int> digits = digitSep(n); 

And then in the for loop, you have to do:然后在for循环中,您必须执行以下操作:

for (int i = 0; i < digits.size(); i++) {
    cout << digits[i] << endl;   
}

or simply:或者简单地说:

for (int i : digits) {
    cout << i << endl;    
}

There are two issues here这里有两个问题

  1. vector<int> digitSep(n); is a constructor call, initializing vector containing n elements each initialized to zero.是一个构造函数调用,初始化包含 n 个元素的向量,每个元素都初始化为零。
  2. Main function knows nothing about variable vector<int> digits;主要 function 对变量vector<int> digits; since it is in local scope of std::vector<int> digitSep(int d) function因为它在std::vector<int> digitSep(int d) function 的本地 scope

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM