[英]C++ pointers vector
我创建了一个读取列表的方法(bool readList(vector a))。 我想在主要创建一个向量作为参数发送到此方法。 例如:
bool readList(vector<int> a){
//Fill...
}
void main(){
vector<int> my_vector;
readList(my_vector);
//work with my vector
}
我应该使用指针正确吗? 但是如何? 我已经尝试了几种可能性,但没有一种起作用。
现在你传递a
由值(制作副本),修改它,然后丢弃结果。 你应该通过a
参考,而不是:
// a passed by reference
bool readList(vector<int>& a){
//Fill...
}
void main(){
vector<int> my_vector;
readList(my_vector); // inside readList a will now refer to my_vector
//work with my vector
}
另外,您应该将main
的签名更改为return int
。
您需要使用参考 。
bool readList(vector<int>& a)
这意味着,任何改变做出a
传播到它的源代码, my_vector
。
在这种情况下,您想通过引用传递 。 为此,将您的方法定义更改为:
bool readList(vector<int>& a){
//Fill...
}
就像STL算法一样,您可以更改readList
以采用如下所示的输出迭代器:
#include <iterator>
#include <vector>
template<class OutputIterator>
OutputIterator readList(OutputIterator result) {
// For example: Adds 0, 1, 2, 3, 4
for (int i = 0; i < 5; i++)
*result++ = i;
return result;
}
int main() {
std::vector<int> my_vector;
readList(std::back_inserter(my_vector));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.