I am trying to write a simple C++ function using iterator for a vector as follows:
#include <iostream>
#include<vector>
#include<sstream>
using namespace std;
using vit = vector<string>::iterator;
void print(const vector<string>& s) {
for(vit it = s.begin(); it != s.end(); ++it ){
cout << *it << endl;
}
}
int main() {
std:: vector<int> v;
for(int i = 0; i < v.size(); ++i)
v[i] = 5 - i;
print(v);
return 0;
}
But I get a list of error including:
error: no matching function for call to print
I thought it might be because I used iterator instead of const_iterator, but the error persists after I fixed it. Why is that happening? Thanks!
print() only accepts an std::vector<string>. You're passing an std::vector<int> which is not the same thing.
If you want to be able to pass any std::vector you want, you'll need to create a template:
template <class type>
void print(const vector<type>& s) {
for(auto it = s.begin(); it != s.end(); ++it ){ // vit is only for a std::vector<string>
cout << *it << endl;
}
}
If you're attached to using vit, you could make that a template as well:
template <class type>
using vit = vector<type>::iterator;
template <class type>
void print(const vector<type>& s) {
for(vit<type> it = s.begin(); it != s.end(); ++it ){ // vit now works with any type
cout << *it << endl;
}
}
Related
using VS2017 and the code:
template <typename T>
void showset(vector<T> v)
{
for (vector<T>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it;
}
cout << endl;
}
the error is :
error C2760: syntax error: unexpected token , expected ';'
The question is how to use the iterator of template
First note that if referring to a template argument dependent name like vector<T>::iterator here, then you need to put typename prior. Furthermore, depends on what T is, this would only compile if std::cout's operator<< is accepting this T. This, for example, compiles just fine:
#include <iostream>
#include <vector>
template <typename T>
void showset(std::vector<T> v)
{
for (typename std::vector<T>::iterator it = v.begin(); it != v.end(); it++)
{
std::cout << *it;
}
std::cout << std::endl;
}
struct foo
{
};
int main()
{
showset(std::vector<int>{1,2,3});
//showset(std::vector<foo>{}); // Error: `cout` doesn't take `foo`s.
return 0;
}
With the auto-enhanced syntax of C++11, showset() could be written like this, and then the typename has no use : )
template <typename T>
void showset(std::vector<T> v)
{
for (auto it = v.begin(); it != v.end(); it++)
{
std::cout << *it;
}
std::cout << std::endl;
}
Also since C++11, you can use the range-based for loop to achieve the same as in your original snippet:
template <typename T>
void showset(std::vector<T> v)
{
for (auto& ref : v)
{
std::cout << ref;
}
std::cout << std::endl;
}
As with the lase version, because you're not referring here to the iterator type there's nothing to put typename for.
Do note that in both versions you are taking parameter v by value. Hence, you're copying the entire vector for each function call. As the code is given in the question, there seem to be no reason for this and so you should be passing it by reference, and make it a const one too as you're not modifying v anywhere inside of showset():
void showset(const std::vector<T>& v);
and then in the non-range-based for loop version don't forget to change the loop statement accordingly:
for (typename std::vector<T>::const_iterator it = v.begin(); it != v.end(); it++)
The good aproch to this looks like this:
template <typename T>
void showset(const T& v)
{
for (auto const &x : v)
{
cout << x;
}
cout << endl;
}
Or without range loop:
template <typename T>
void showset(const T& v)
{
for (auto it = std::begin(v); it != std::end(v); ++it)
{
cout << *it;
}
cout << endl;
}
Edit:
But I'm usually using something more complex. More or less it looks like this:
template<typename T>
class LogContainerHelper {
LogContainerHelper(const T& v
size_t maxFront,
size_t maxTail)
: mContainer{ v }
, mMaxFront{ maxFront }
, mMaxTail{ maxTail }
{}
std::ostream &printTo(std::ostream &out) const {
// here I usually have something more complex
// depending on mMaxFront and mMaxTail values,
// don't have time to recreate that now
auto it = std::begin(mContainer);
auto end = std::end(mContainer);
out << '[';
if (it != end) {
out << *it;
++it;
}
for (; it != end; ++it)
{
out << ", " << *it;
}
return out << ']';
}
private:
const T &mContainer;
size_t mMaxFront;
size_t mMaxTail;
};
template<typename T>
std::ostream &operator <<(std::ostream &out, const LogContainerHelper<T> &helper) {
return helper.printTo(out);
}
template<typename T>
auto LogContainer(const T& v,
size_t maxFront = std::numeric_limits<size_t>::max(),
size_t maxTail = 0)
-> LogContainerHelper<T> {
return LogContainerHelper<T>{ v, maxFront, maxTail };
}
So later I can do that:
cout << "Main containter is: " << LogContainer(v) << '\n';
so far I wrote this:
template <typename TType>
void print_vector(const std::vector<TType>& vec)
{
typename std::vector<TType>::const_iterator it;
std::cout << "(";
for(it = vec.begin(); it != vec.end(); it++)
{
if(it!= vec.begin()) std::cout << ",";
std::cout << (*it);
}
std::cout << ")";
}
template<>
template <typename T2>
void print_vector(const std::vector< std::vector<T2> >& vec)
{
for( auto it= vec.begin(); it!= vec.end(); it++)
{
print_vector(*it);
}
}
The first function works fine for things like std::vector< double> and so on. Now I want to be able to print std::vector< std::vector< TType>> things as well. The second part doesn't compile, but that's the "idea" I have of solving my task. Any suggestions on how to achieve that kind of behavior?
Compilation Error: too many template-parameter-lists
Remove the template<> part, function template overloading would work fine.
template <typename TType>
void print_vector(const std::vector<TType>& vec)
{
typename std::vector<TType>::const_iterator it;
std::cout << "(";
for(it = vec.begin(); it != vec.end(); it++)
{
if(it!= vec.begin()) std::cout << ",";
std::cout << (*it);
}
std::cout << ")";
}
template <typename T2>
void print_vector(const std::vector< std::vector<T2> >& vec)
{
for( auto it= vec.begin(); it!= vec.end(); it++)
{
print_vector(*it);
}
}
You may actually want to go for a more generic solution to the problem, allowing to print pretty much any iterable type:
#include <vector>
#include <iostream>
template <typename Iterable>
std::ostream& operator<<(std::ostream& os, const Iterable& vals)
{
for (const auto& val : vals)
os << val << std::endl;
return os;
}
int main()
{
auto simple_vec = std::vector<int>{3, 5 , 7};
std::cout << simple_vec;
auto nested_vec = std::vector<std::vector<int>>{{1, 2}, {3, 4}};
std::cout << nested_vec;
}
For further improvements on this solution, you could try using SFINAE, to make sure the templated << is only available for iterable types.
If you make your function to print base types and override for vector using itself recursively:
template<typename T>
void print( const T &t )
{
std::cout << t;
}
template<typename T>
void print( const std::vector<T> &v )
{
std::cout << '[';
for( auto it = v.begin(); it != v.end(); ++it ) {
if( it != v.begin() ) std::cout << ',';
print( *it );
}
std::cout << ']';
}
then you do not need to write special one for vector of vectors or vector of vectors of vectors and so on.
live example
I've just started to code in C++, so i'm new to STL .
Here i'm trying to iterate over a graph stored as vector of vectors.
#include <iostream>
#include <vector>
#include <iostream>
using namespace std;
int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;
for (it = adj.begin(); it != adj.end(); it++)
{
cout << (*it) << endl;
if ((*it) == x)
for (i = (*it).begin(); i != (*it).end(); i++)
{
cout << (*i) << endl;
if ((*i) == y)
return 1;
}
}
return 0;
}
int main()
{
}
I'm getting an error std::vector<int> is not derived from const gnu cxx. Can someone point me in the right direction ?
*it pointing to vector not int that is why you are getting error
following code may work for you
#include <vector>
#include <iostream>
using namespace std;
int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;
for (it = adj.begin(); it != adj.end(); it++)
{
cout << (*(*it).begin()) << endl;
if (( (*(*it).begin())) == x)
for (i = (*it).begin(); i != (*it).end(); i++)
{
cout << (*i) << endl;
if ((*i) == y)
return 1;
}
}
return 0;
}
int main()
{
}
for accessing first element of the vector of the use
(*(*it).begin()) in place of (*it)
if you are studying graph then use array of vector. for more details please go through following url
C++ Depth First Search (DFS) Implementation
cout << (*it) << endl;
Here, you declared it as a:
vector<vector<int> >::iterator it;
Therefore, *it is a:
vector<int>
So you are attempting to use operator<< to send it to std::cout. This, obviously, will not work. This is equivalent to:
vector<int> v;
cout << v;
There is no operator<< overload that's defined for what cout is, and a vector<int>. As you know, in order to print the contents of a vector, you have to iterate over its individual values, and print its individual values.
So, whatever your intentions were, when you wrote:
cout << (*it) << endl;
you will need to do something else, keeping in mind that *it here is an entire vector<int>. Perhaps your intent is to iterate over the vector and print each int in the vector, but you're already doing it later.
Similarly:
if ((*it) == x)
This won't work either. As explained, *it is a vector<int>, which cannot be compared to a plain int.
It is not clear what your intentions are here. "Graph stored as a vector or vectors" is too vague.
The following code compiles with the option std=c++11. But x is missing in vector<vector<int>>. If adj had type vector<pair<int, vector<int>>> it would better match.
The following code compiles for vector<vector<int>> but it doesn't use x.
using std::vector;
using std::pair;
using std::cout;
using std::endl;
int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;
for(it=adj.begin();it!=adj.end();it++)
{
// cout << (*it) << endl;
for (const auto& nexts: *it)
cout << nexts << ' ';
cout << endl;
for(i=(*it).begin();i!=(*it).end();i++)
{
cout << (*i) << endl;
if((*i)==y)
return 1;
}
}
return 0;
}
This code compiles with <vector<pair<int, vector<int>>> and uses x.
using std::vector;
using std::pair;
using std::cout;
using std::endl;
int reach(vector<pair<int, vector<int> > > &adj, int x, int y) {
vector<pair<int, vector<int> > >::iterator it;
vector<int>::iterator i;
for(it=adj.begin();it!=adj.end();it++)
{
cout << it->first << endl;
if (it->first == x)
for(i=it->second.begin();i!=it->second.end();i++)
{
cout << (*i) << endl;
if((*i)==y)
return 1;
}
}
return 0;
}
Wrap it up in an iterator.
This can be templated for reuse.
Here is a minimal working example for the std::vector<T> container:
#include <iostream>
#include <utility>
#include <vector>
/// Iterable vector of vectors
/// (This just provides `begin` and `end for `Vector2Iterable<T>::Iterator`).
template<typename T>
class VovIterable
{
public:
static const std::vector<T> EMPTY_VECTOR;
/// Actual iterator
class Iterator
{
typename std::vector<std::vector<T>>::const_iterator _a1;
typename std::vector<T>::const_iterator _a2;
typename std::vector<std::vector<T>>::const_iterator _end;
public:
/// \param a1 Outer iterator
/// \param a2 Inner iterator
/// \param end End of outer iterator
explicit Iterator(typename std::vector<std::vector<T>>::const_iterator a1, typename std::vector<T>::const_iterator a2, typename std::vector<std::vector<T>>::const_iterator end)
: _a1(a1)
, _a2(a2)
, _end(end)
{
Check();
}
bool operator!=(const Iterator &b) const
{
return _a1 != b._a1 || _a2 != b._a2;
}
Iterator &operator++()
{
++_a2; // Increment secondary
Check();
return *this;
}
const T &operator*() const
{
return *_a2;
}
private:
void Check()
{
while (true)
{
if (_a2 != _a1->end()) // Is secondary live?
{
break;
}
// Increment primary
_a1++;
if (_a1 == _end) // Is primary dead?
{
_a2 = EMPTY_VECTOR.end();
break;
}
_a2 = _a1->begin(); // Reset secondary
}
}
};
private:
std::vector<std::vector<T>> _source;
public:
explicit VovIterable(std::vector<std::vector<T>> source)
: _source(std::move(source))
{
}
/// Start of vector of vectors
[[nodiscard]] Iterator begin() const
{
if (this->_source.empty())
{
return end();
}
return Iterator(this->_source.cbegin(), this->_source.cbegin()->cbegin(), this->_source.cend());
}
/// End of vector of vectors
[[nodiscard]] Iterator end() const
{
return Iterator(this->_source.cend(), EMPTY_VECTOR.end(), this->_source.cend());
}
};
template<typename T>
const std::vector<T> VovIterable<T>::EMPTY_VECTOR = {0};
/// Sample usage
int main()
{
std::vector<std::vector<int>> myVov{{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for (int i: VovIterable(myVov))
{
std::cout << i << std::endl;
}
return 0;
}
I've been playing with C++11 functional in order to do the same as python's itertools.combinations(input, 2), so far this is what I have:
EDIT removed outer lambda as suggested by #DavidRodrÃguez-dribeas
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
template <class T>
function<pair<T*, T*>()> combinations(vector<T> & input) {
auto it1 = input.begin();
auto end = input.end();
auto it2 = next(it1);
return [=]() mutable {
if (it2 == end) {
it1++;
it2 = next(it1);
}
if (it2 != end)
return pair<T*,T*>(&(*it1), &(*it2++));
return pair<T*,T*>(&*end, &*end);
};
};
int main (void) {
vector<int> numbers{1,2,3,4,5,6};
auto func = combinations(numbers);
while ( true ) {
auto i = func();
if (i.first == &*(numbers.end())) break;
cout << *(i.first) << ',' << *(i.second) << endl;
}
return 0;
};
I'm not happy with the method used to iterate over the combinations any advice on cleaning it up?
Here is documentation and code on my favorite way of doing this. And here is how that library would be used for your example:
#include <iostream>
#include <vector>
#include "combinations"
using namespace std;
int main (void) {
vector<int> numbers{1,2,3,4,5,6};
for_each_combination(numbers.begin(), numbers.begin()+2, numbers.end(),
[](vector<int>::const_iterator b, vector<int>::const_iterator e)
{
if (b != e)
{
cout << *b;
for (auto i = b+1; i != e; ++i)
cout << ',' << *i;
cout << endl;
}
return false;
});
}
1,2
1,3
1,4
1,5
1,6
2,3
2,4
2,5
2,6
3,4
3,5
3,6
4,5
4,6
5,6
Should the need arise, it is trivial to change the example use to consider 3 or 4 items at time instead of 2. One can also deal with various permutations k out of N at a time.
Update
Adding a level of indirection to illustrate how you would deal with a vector of items that were not efficient at moving/swapping around in the vector:
#include <iostream>
#include <vector>
#include "combinations"
using namespace std;
int main (void) {
vector<int> numbers{1,2,3,4,5,6};
vector<vector<int>::const_iterator> num_iters;
num_iters.reserve(numbers.size());
for (auto i = numbers.begin(); i != numbers.end(); ++i)
num_iters.push_back(i);
for_each_combination(num_iters.begin(), num_iters.begin()+2, num_iters.end(),
[](vector<vector<int>::const_iterator>::const_iterator b,
vector<vector<int>::const_iterator>::const_iterator e)
{
if (b != e)
{
cout << **b;
for (auto i = b+1; i != e; ++i)
cout << ',' << **i;
cout << endl;
}
return false;
});
}
I found out that Oliver Kowalke's coroutine library has been accepted by Boosts peer review and should be included hopefully in the next version. Jumping the gun a bit I gave it a go by using the coroutine branch of the boost-dev repo (https://gitorious.org/boost-dev/boost-dev).
g++ -I path/to/boost-dev -std=c++11 test_code.cpp -o run_test_code -static -L path/to/boost-dev/stage/lib/ -lboost_context
#include <boost/coroutine/all.hpp>
#include <boost/bind.hpp>
#include <boost/range.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace boost;
template <typename T>
using coro_pairT_void = coroutines::coroutine<pair<T&,T&>(void)>;
template <typename T>
void combinations(typename coro_pairT_void<T>::caller_type & self, vector<T> & input ) {
for (auto it1 = input.begin(), itend = input.end(); it1 != itend; it1++) {
for (auto it2 = std::next(it1); it2 != itend; it2++) {
self(pair<T&, T&>(*it1,*it2));
}
}
};
int main( void ) {
vector<int> numbers{1,2,3,4,5,6};
coro_pairT_void<int> func(bind(combinations<int>, _1, numbers));
for (auto it(begin(func)), itend(end(func)); it != itend; ++it) {
cout << it->first << ',' << it->second << endl;
}
return 0;
};
I would like to know if I can have a generic iterator to access the elements in the the vectors. I have for different vectors but only one function to display the elements.
If I can have a generic iterator than my method can work out smoothly. Please advice if it is possible.
Point2,Point3,Line2,Line3 are 4 different classes. The method takes in a vector object which I have created in another method.
template <typename VecObject>
void Display(VecObject v) {
if (filterCriteria == "Point2") {
vector<Point2>::iterator it;
} else if (filterCriteria == "Point3") {
} else if (filterCriteria == "Line2") {
} else if (filterCriteria == "Line3") {
}
for ( it = v.begin(); it!=v.end(); ++it) {
cout << *it << endl;
}
}
This what i used to do ealier and it work find. I now need to to implement using iterators
//for (int i = 0; i < v.size(); i++) {
// cout << v[i];
// }
You have access to a vector's iterator types via iterator and const_iterator, so you need no switching:
template <typename VecObject>
void Display(const VecObject& v) {
typename VecObject::const_iterator it;
for ( it = v.begin(); it!=v.end(); ++it) {
cout << *it << endl;
}
}
Note that I changed the signature to take a const reference as opposed to a value. With the original signature, you would be needlessly copying the vector each time you call the function.
Alternatively, you can implement the function to take two iterators:
template <typename Iterator>
void Display(Iterator first, Iterator last) {
for (Iterator it = first; it!=last; ++it) {
cout << *it << endl;
}
}
and call it like this:
Display(v.begin(), v.end());
template<typename VectorObject>
void Display(VecObject v) {
typename VectorObject::const_iterator it = v.begin();
for (; it!=v.end(); ++it) {
cout << *it << endl;
}
}
Assume that your VectorObject implements iterators you can access to it's iterator type directly.
Usage:
int main()
{
std::vector<int> intv(2, 5);
std::vector<float> fv(2, 10);
Display(intv);
Display(fv);
return 0;
}