This question already has answers here:
c++ change function's variable argument
(2 answers)
Closed 8 years ago.
Say I have
string stringInput = "hello";
alter(stringInput);
cout << stringInput;
and a function:
void alter(string stringIn){
stringIn[0] = stringIn[3];
}
Ideally I would want cout to produce "lello". But right now it simply returns "hello" as originally. I know this has something to do with addresses and pointers... how would I achieve this?
It's actually just because a new copy of the string is created for use in the function. To modify the string directly in the function add an & before the string name in the function header like this:
void alter(string &stringIn){
That passes the string by reference. Otherwise you could just return a string from the function.
All you need to do is to pass the string by reference:
void alter(string& stringIn){
// ^
stringIn[0] = stringIn[3];
}
You should also modify accordingly any function declarations you have for alter().
Your stringIn is a local variable. So when you pass it on the function as a value it just makes a new stringIn with different address. So the changes you are making in alter is only affecting the new stringIn. You need to recieve the reference of the stringIn in alter to make it work.
void alter(string& stringIn){
stringIn[0] = stringIn[3];
}
Related
This question already has answers here:
Which is more efficient: Return a value vs. Pass by reference?
(7 answers)
Closed 2 years ago.
I have been learning C++ and came across a function, but the return type was a vector.
Here is the code:
vector<Name> inputNames() {
ifstream fin("names.txt");
string word;
vector<Name> namelist;
while (!fin.eof()) {
Name name;
fin >> name.first_name;
fin >> name.last_name;
namelist.push_back(name);
}
return namelist;
}
name is part of a struct defined as:
struct Name {
string first_name;
string last_name;
bool operator<(const Name& d) const {
return last_name > d.last_name;
}
void display() {
cout << first_name << " " << last_name << endl;
}
};
What is the purpose of using vector< Name>inputName()? What is it doing?
And why can I just not create a void function and pass a vector through it?
I.e.:
void input(vector<Name>&v){
ifstream fin("names.txt");
string word;
while (!fin.eof()) {
Name name;
fin >> name.first_name;
fin >> name.last_name;
v.push_back(name);
}
}
Your question is basically: Do I return by value or do I use an output argument?
The general consensus in the community is to return by value, especially from C++17 on with guaranteed copy elision. Although, I also recommend it C++11 onwards. If you use an older version, please upgrade.
We consider the first snippet more readable and understandable and even more performant.
From a callers perspective:
std::vector<Name> names = inputNames();
It's clear that inputNames returns you some values without changing the existing state of the program, assuming you don't use global variables (which you actually do with cin).
The second code would be called the following way:
std::vector<Name> names;
// Other code
inputNames(names);
This raises a lot of questions:
does inputNames use the names as input or does it extend it?
if there are values in names, what does the function do with it?
does the function have a return value to indicate success?
It used to be good practice when computers were slow and compilers had troubles optimizing, though, at this point, don't use it for output arguments.
When do you use the last style: if you want an in-out argument. In this case, if you intend to append, the vector already had data, and that actually makes sense.
This basically mirrors the mathematical definition of a function as...
...a relation that associates an input to a single output.
While you could write void functions that modify their parameters, this has disadvantages:
Expression of intent. Consider a function taking multiple parameters. Which ones are input, which ones are output?
Clarity of purpose. A function modifying multiple values at once is usually (not always) attempting to do too many things at once. Focussing on one return value per function helps with keeping your program logic under control.
RAII. You can't use a void function to initialize a variable, meaning you would have to declare that variable first (initialized to some "default" value), then initialize it to the desired value.
There are languages that work without return values, using "out parameters" instead. You can do it this way in C++ as well. But all in all, using return values as the one output of a function helps the structure of your program.
vector<Name> is the return value of the method. It will create a new object with a vector of the structs.
Your implementation is called "call by reference". It will pass the pointer to an existing vector. As a example, with the call by the reference implementation, you could call input(vector<Name>&v) multiple times and your preexisting vector will have multiple times the content. If you would to it with the vector return value, it would always create a new object with only one iteration of data.
This question already has answers here:
Convert string to variable name or variable type
(7 answers)
Closed 5 years ago.
If the title is not so suggestive I hope the explanation might help you understand my problem.
I have a function which sets some variables value. But the variables name I would like to provide it as a string, this way:
void setValue( const std:: string& variable_name, int value){ variable_name=value;}
then when I call this function like this:
setValue("variable", 10);
I will expect to execute set variable=10;
Any idea if this approach is possible or other ways I could have this behaviour?
Thanks!
It is not possible to magically retrieve a variable from a run-time string. You need to provide a mapping in advance, which is probably not what you want. E.g.
int& getFromName(const std::string& s)
{
if(s == "variable") return variable;
if(s == "foo") return foo;
// ...
}
This question already has answers here:
Simple C++ - about strings and concatenation and converting int to string [duplicate]
(3 answers)
Closed 6 years ago.
This may seem trivial to normal C++ users, but I'm currently relearning C++ all over again. I have a function that takes in an int& and I would like to add that value to a string for a print statement. So, I have something like this:
std::string getTest(void* dataGroup, int& xWidth, int& yHeight)
{
std::string results = "";
results += "\nxWidth is: " + xWidth;
return results;
}
which fails to run when I call it. What is the proper way to convert the pass-by-reference int& value into a form that can be added to a string?
std::to_string(xWidth).
The & is pretty much irrelevant. to_string takes the int by value, so how your function takes it doesn't matter: by value, lvalue ref, rvalue ref, const or non-const... all will work.
This question already has answers here:
What is a reference variable in C++?
(12 answers)
Closed 7 years ago.
I want to implement a function with a parameter that will receive a string result:
bool function (entry parameter, std::ostringstream & var)
I'm not sure about what it is, pointer ?
Should I do something special about it or just: var << result ?
The return value is boolean but we will need var after
& means it is a reference, not a pointer. See Andrew's comment link. You do not need to delete var, if that is what you mean by "something special." Given the method signature you provided, the code:
var << result;
should work just fine, assuming "result" is something sane. If you need more information, you may need to post a MCVE.
This question already has answers here:
What is a reference variable in C++?
(12 answers)
Closed 7 years ago.
The function get of an ifstream reads the next character and stores it in the argument you pass to the function. Example program:
#include <iostream>
#include <fstream>
int main () {
std::ifstream is("input.txt"); // open file
char c;
while (is.get(c)) // loop getting single characters
std::cout << c;
is.close(); // close file
return 0;
}
This works great but I am puzzled by how c can be changed by the function get as it is not passed by its pointer. I was told, some time ago, that modifying a variable within a function cannot change its value outside the function. And that's the whole purpose of pointers, right -- manipulating an object created outside the function. So how can c be changed here?
I guess there is something obvious that I don't understand here?
The member function std::istream::get() uses a reference:
istream& get (char& c);
This means that the function accesses directly to the variable passed as a parameter.
If you're not familiar with references, here you can learn more.
"So how can c be changed here?"
As from the reference documentation std::ifstream::get() uses a parameter passed by reference for the char variable
basic_istream& get( char_type& ch );
so it alters it by using this reference.