I have a function where I have to modifiy the values of a vector. is it a good practice in C++ to return the vector?
vector<string> RemoveSpecialCharacters(vector<string> words)
{
for (vector<string>::iterator it=words.begin(); it!=words.end(); )
{
if(CheckLength(*it) == false)
{
it = words.erase(it);
}
else{
++it;
}
}//end for
return words;
}
void RemoveSpecialCharacters(vector<string> & words)
{
for (vector<string>::iterator it=words.begin(); it!=words.end(); )
{
if(CheckLength(*it) == false)
{
it = words.erase(it);
}
else{
++it;
}
}//end for
}
The syntax for modifying values from a vectorvectorname. assign(InputIterator first, InputIterator last) Parameters: first - Input iterator to the initial position range. last - Input iterator to the final position range.
To replace an element in Java Vector, set() method of java. util. Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.
vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.
vector<SalesItem> *getSalesItems(); returns a pointer and does not return a reference. void Invoice::getSalesItems() doesn't return anything. The function definition in the class and the declaration must be the same: vector<SalesItem> & getSalesItems(); returns a vector by refernece.
Your two functions serve for two different purposes.
Function 1: works as remove_copy
. It will not modify the existing container; it makes a copy and modifies that instead.
Function 2: works as remove
. It will modify the existing container.
It's somewhat subjective. I personally would prefer the latter, since it does not impose the cost of copying the vector onto the caller (but the caller is still free to make the copy if they so choose).
In this particular case I'd choose passing by reference, but not because it's a C++ practice or not, but because it actually makes more sense (the function by its name applies modification to the vector). There seems to be no actual need to return data from the function.
But that also depends on purpose of the function. If you always want to use it in the following way:
vec = bow.RemoveSpecialCharacters(vec);
Then absolutely first option is a go. Otherwise, the second one seems to be more appropriate. (Judging by the function name, the first one seems to me to be more appropriate).
In terms of performance, the first solution in modern C++11 world will be more-less a few assignments slower, so the performance impact would be negligible.
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