C++ function that takes an OutputIterator and writes to it
I'm trying to write a C++ function that takes an OutputIterator and writes values to it, but I'm getting various problems. When I pass in a list<> iterator, the list is not filled, and when I pass in a vector<> iterator, I get a segmentation fault (on Linux).
I followed the discussions from "populating an std::[container] from a function by passing an output iterator" and "How to write a funct开发者_如何学Goion that takes an iterator or collection in a generic way?".
Any ideas? I would like to invoke the insertValues() code with the output container's begin(), just like I would with other STL functions such std:copy().
#include <cstdio>
#include <list>
#include <vector>
using namespace std;
template<typename OutputIterator>
void insertValues(OutputIterator result)
{
for (int i = 0; i < 10; i++)
{
*(result++) = i;
}
}
int main(int argc, char **argv)
{
// This code produces 0 items in the list.
list<int> values_list;
insertValues(values_list.begin());
printf("values has %d items\n", (int) values_list.size());
// This code produces a seg fault.
vector<int> values_vector;
insertValues(values_vector.begin());
printf("values has %d items\n", (int) values_vector.size());
}
Your code breaks, because neither the list nor the vector have enough elements. Note that an output iterator doesn't add elements, it simply writes to existing elements.
Thus, you could rewrite it as follows:
template<typename Container>
void insertValues(Container &result)
{
for (int i = 0; i < 10; i++)
{
result.push_back(i);
}
}
and in main
:
insertValues(values_list);
insertValues(values_vector);
Alternatively, you could use an iterator that performs a push_back
operation. This is in the standard library under the name back_inserter
(#include <iterator>
). Using that, and not modifying your insertValues
code:
insertValues(back_inserter(values_list));
insertValues(back_inserter(values_vector));
精彩评论