I have this example code that doesn't compile:
#include <iostream>
#include <vector>
using std::endl; using std::cin; using std::cout;
using std::vector;
int main()
{
vector<int> vi, seg;
vi.push_back(3);
vi.push_back(4);
vi.push_back(5);
vi.push_back(6);
vi.push_back(7);
vector<int>::const_iterator ci_s开发者_Go百科tart = vi.begin();
vector<int>::const_iterator ci_actual = vi.begin();
while (ci_actual != vi.end())
{
seg = vi(ci_start, ci_actual);
cout << "......" ;
for (const vector<int>::const_iterator ci = vi.begin();
ci != vi.end(); ++ci)
cout << *ci << " ";
cout << endl;
++ci_actual;
}
}
What I want is to pass increasing parts of vector vi
(that is going to take some million elements) to a function (not shown). These segments are considered from the begining of vi
up to where actual
is at the moment.
seg
that was supposed to have part of vi.
Desired output would be:
3
3 4 3 4 5 3 4 5 6 3 4 5 6 7Is seg
not supposed to hold a copy of elements of vi
denoted by iterators ci_start
and ci_actual
?
To pass the ever increasing part of vi
to the function I refered (absent), can I do it faster without copying the elements of vi
to another vector and just pass a reference to a segment of vi
?
for (const vector<int>::const_iterator ci = vi.begin(); ci != vi.end(); ++ci)
You are declaring a const const_interator here. Meaning whey you try to call ++ci, the compiler will yell at you for trying to modify a constant variable. This should fix that compiler error:
for (vector<int>::const_iterator ci = vi.begin(); ci != vi.end(); ++ci)
If you have a compiler error, please tell us what it is. It looks like this:
seg = vi(ci_start, ci_actual);
Should be
vector<int> seg(ci_start, ci_actual);
And remove the declaration of seg at the top of main().
And your for loop should use seg.begin()/seg.end() if you want to print the segment
Re: your follow-on question about how to call a helper function that you want to operate on a subrange of your large vector...
First, this stackoverflow question might be useful. The accepted "just pass a pair of iterators" answer was exactly what I was about to suggest.
Second, if you're OK using the boost libraries, the vector proxy libraries may be useful.
int main()
{
vector<int> vi;
vi.push_back(3);
vi.push_back(4);
vi.push_back(5);
vi.push_back(6);
vi.push_back(7);
//the end of the sequence
vector<int>::iterator seq_end = vi.begin() + 1;
while (seq_end != vi.end())
{
cout << "......" ;
for (vector<int>::iterator ci = vi.begin(); ci != seq_end; ++ci)
cout << *ci << " ";
cout << endl;
any_function(vi.begin(), seq_end);
++seq_end;
}
}
void any_function(const vector<int>::iterator& seq_start,
const vector<int>::iterator& seq_end)
{
...
}
this code make it, analyze and repair your mistakes.
精彩评论