[英]Why does my program display the null vector?
我不明白為什么我的程序顯示 nul 向量:
#include <vector>
#include <iostream>
template <class T>
std::vector<int> collect_values(const T & t, int first, int next_to_last) {
std::vector<int> v(next_to_last-first);
for(int i=0; i<next_to_last - first; i++) {
v[i] = t(v[i]);
}
return v;
}
int main() {
int a=0, b=5;
auto square=[](int i) {return i*i;};
std::vector<int> v;
v = collect_values(square,a,b);
for(int i=0; i<b-a; i++) {
std::cout << v[i] << std::endl;
}
return 0;
}
好的,在循環結束時,將刪除 function 中的向量。 但是我存儲了function,所以應該存儲向量,對吧? 如果 collect_values 循環中的向量 v 已被刪除,為什么我會有一個包含 5 個 null 單元格的向量而不是空向量?
在收集值中
std::vector<int> v(next_to_last-first);
因為next_to_last-first
值為 5 你創建了一個大小為 5 的向量,其中所有元素的值為 0
v[i] = t(v[i]);
因為t返回平方或其參數但每個元素的值為 0 向量不變重新分配所有條目為 0
return v;
返回包含 5 次 0 的向量
在主要
v = collect_values(square,a,b);
v分配給包含 5 次 0 的向量
for(int i=0; i<ba; i++) { std::cout << v[i] << std::endl; }
然后在一行上打印 5 次 0
如果你替換v[i] = t(v[i]);
由v[i] = t(i);
在collect_values你將打印
0
1
4
9
16
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.