How can I pass a part of a vector as a function argument?
A common approach is to pass iterator ranges. This will work with all types of ranges, including those belonging to standard library containers and plain arrays:
template <typename Iterator>
void func(Iterator start, Iterator end)
{
for (Iterator it = start; it !=end; ++it)
{
// do something
}
}
then
std::vector<int> v = ...;
func(v.begin()+2, v.end());
int arr[5] = {1, 2, 3, 4, 5};
func(arr+2, arr+5);
Note: Although the function works for all kinds of ranges, not all iterator types support the increment via operator+
used in v.begin()+2
. For alternatives, have a look at std::advance
and std::next
.
Is it possible to send part of vector as a vector to a function?
Use iterators as the parameters to the range-based function, and pass in the required range. Your code in the function become
funcWithRange(v.cbegin()+10, v.cbegin()+50);
with function signature
void funcWithRange(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last)
This could be generalized by making this a function template with the vector
member type as its template parameter, or still further to any container supporting this type of range iteration. As noted in the comments, <algorithm>
has many examples of this pattern.
std::distance(first, last);
will return the desired altered size. I don't think you can get closer to meeting your requirements without making a physical copy.
How to pass vector of vector as default argument in functions, C++
The problem is that we cannot bind an lvalue reference to a non-const object to a temporary of the corresponding type.
For instance,
int &ref = 5; //THIS WILL NOT WORK
const int &REF = 5; //THIS WILL WORK
To solve this error you can make the last parameter name
to be an lvalue reference to a const object which is allowed to bound to a temporary as shown below:
void Box_2(vector<vector<int>> &v,
string text1 = "",
string text2 ="",
//---------vvvvv------------------------------------->low level const added here
const vector<vector<int>> &trace = {}
);
Note that with above you won't be able to change name
. This is a consequence of adding the low-level const
.
You can also just leave off the default arguments altogether as shown below:
void Box_2(vector<vector<int>> &v, string text1, string text2, vector<vector<int>> &trace);
Now you will be able to change the underlying vector to which name
is bound.
How to pass a vector to a function?
It depends on if you want to pass the vector
as a reference or as a pointer (I am disregarding the option of passing it by value as clearly undesirable).
As a reference:
int binarySearch(int first, int last, int search4, vector<int>& random);
vector<int> random(100);
// ...
found = binarySearch(first, last, search4, random);
As a pointer:
int binarySearch(int first, int last, int search4, vector<int>* random);
vector<int> random(100);
// ...
found = binarySearch(first, last, search4, &random);
Inside binarySearch
, you will need to use .
or ->
to access the members of random
correspondingly.
Issues with your current code
binarySearch
expects avector<int>*
, but you pass in avector<int>
(missing a&
beforerandom
)- You do not dereference the pointer inside
binarySearch
before using it (for example,random[mid]
should be(*random)[mid]
- You are missing
using namespace std;
after the<include>
s - The values you assign to
first
andlast
are wrong (should be 0 and 99 instead ofrandom[0]
andrandom[99]
Passing a vector as argument to function
Use the referenced type
void Foo(std::vector<bool> &Visited, int actual element);
Otherwise the function deals with a copy of the original vector.
Here is a dempnstrative program
#include <iostream>
#include <vector>
void f( std::vector<int> &v )
{
v.assign( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } );
}
int main()
{
std::vector<int> v;
f( v );
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
}
The program output is
0 1 2 3 4 5 6 7 8 9
How to pass a vector into a function parameter (do I need pointers?)
It's quite possible, but you are passing an element of the vector, not the vector itself:
void func(vector<int> *vect) {
vect->push_back(30); // <-- pointer type expression
}
int main() {
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
func(&vect); // <-- pass the vector
for (size_t i = 0; i < vect.size(); i++) // <-- iterator should be size_t type
cout << vect[i] << " ";
return 0;
}
If you would like to pass a reference to an element of a vector you can do it too, beware, that element must already exist:
void func(int *vect_elem) { //<-- pointer to int parameter
*vect_elem = 30; // <-- assign 30 to the vector element
}
int main() {
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
func(&vect[0]); //<-- reference an existing element of the vector
for (size_t i = 0; i<vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
In this particular case you don't need pointers, a better option is to use references only, like it was already mentioned, since you wouldn't need any dereferencing:
void func(vector<int> &vect) { //<-- parameter reference
vect.push_back(30);
}
int main() {
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
func(vect); // <-- pass the vector
for (size_t i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
void func(int &vect_elem) { //<-- parameter reference
vect_elem = 30;
}
int main() {
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
func(vect[0]); //<-- pass the element
for (size_t i = 0; i<vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
Passing vector by reference to another class/file
- To derived class add one more pointer field:
class DerivedFrame: public OtherFrame {
.......
private:
std::vector<wxString> * pvwsM3 = nullptr;
.......
};
- Modify PassVector() method to fill pointer:
void DerivedFrame::PassVector(std::vector<wxString> & vwsM) {
pvwsM3 = &vwsM;
}
- Use pointer now:
void DerivedFrame::USEvwsM() {
assert(pvwsM3); // Check that we don't have null pointer, you may throw exception instead.
pvwsM3->push_back("Something");
}
- Remaining code is same as you have. Alternatively you may pass vector to constructor of DerivedFrame, which is more reliable than calling PassVector() separately (which you may forget to call, while constructor you always call):
DerivedFrame::DerivedFrame(wxWindow* parent, std::vector<wxString> & vwsM)
: OtherFrame( parent ) {
this->PassVector(vwsM);
}
- If you pass vector of strings to constructor only then you don't need a pointer, but reference in derived class, so instead of pointer field
class DerivedFrame: public OtherFrame {
std::vector<wxString> * pvwsM3 = nullptr;
.......
};
make reference field
class DerivedFrame: public OtherFrame {
std::vector<wxString> & rvwsM3;
.......
};
then remove PassVector() method and add reference initialization in constructor:
DerivedFrame::DerivedFrame(wxWindow* parent, std::vector<wxString> & vwsM)
: OtherFrame( parent ), rvwsM3(vwsM) {}
and use it as a reference (unlike pointer reference doesn't need to be checked for null):
void DerivedFrame::USEvwsM() {
rvwsM3.push_back("Something");
}
Reference compared to pointer has two advantages - it can't be forgotten to be initialized, because with reference you don't need to call PassVector(), and you don't need to check if it is null unlike checking pointer (reference is never null). But reference can be initialized only in constructor, while pointer can be initialized later, far later after object was constructed.
Related Topics
Why Do My Sfinae Expressions No Longer Work with Gcc 8.2
C++ Back End Call the Python Level Defined Callbacks with Swig Wrapper
Emplace an Aggregate in Std::Vector
What Is Double Evaluation and Why Should It Be Avoided
Move the String Out of a Std::Ostringstream
Volatile Struct = Struct Not Possible, Why
Access Violation Writing Location 0Xcccccccc
Gcc Does Not Honor 'Pragma Gcc Diagnostic' to Silence Warnings
Could Not Load Spatialite Extension in Qsqlite ( Qt 5.9)
Use Static_Assert to Check Types Passed to MACro
Array[Byte] to Hbitmap or Cbitmap
C++ Makefile on Linux with Multiple *.Cpp Files
What Happens When Calling the Destructor of a Thread Object That Has a Condition Variable Waiting
How to Use a Constexpr Value in a Lambda Without Capturing It
Priority of Kernel Modules and Sched_Rr Threads
What's the Difference Between Cout<<Cout and Cout<<&Cout in C++