I read that using raw pointers in C++ is bad. Instead we should use auto_ptr. In the below code I am populating a vector in foo() that is created in the main(). Am I doing it right or is there a better way to do without using explicit pointers.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string> *v){
(*v).push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(&v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
C++ uses references for what you are trying to do:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string>& v){
v.push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
References and pointers are similar, with one very important distinction: there is no such thing as a null reference (Constructing one is Undefined Behavior in C++ you can construct one, but doing so is considered a hack).
In C++ you can avoid the pointer and use a pass-by-reference:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void foo(vector<string>& v){
v.push_back(" hru");
}
int main(){
vector<string> v;
v.push_back("hi");
foo(v);
for(int i=0;i<v.size(); i++){
cout << v[i];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With