[英]C++ Function with iterators from templated container
I'm trying to write a basic bucket sort. 我正在尝试编写基本的存储桶排序。 I have a function that takes in the begin and end iterators for a vector.
我有一个函数,它接受矢量的开始和结束迭代器。 I need to have the vector's value_type templated so that I can use it to create a vector of buckets for the sort (using std::numeric_limits).
我需要将向量的value_type模板化,以便可以使用它来创建用于分类的存储桶向量(使用std :: numeric_limits)。 The function is meant for T that's no bigger than short ints.
该函数适用于T,它不大于short int。
Here's the function I've written: 这是我编写的函数:
template<typename T>
typename std::vector<T>::iterator forwardIterator;
void bucketSort(forwardIterator begin, forwardIterator end) {
std::vector<unsigned> bucketVec(std::numeric_limits<T>::max() + 1, 0);
for (auto it = begin; it != end; it++)
bucketVec[*it]++;
auto it = begin;
for (unsigned j = 0; j < bucketVec.size(); j++)
for (unsigned k = 0; k < bucketVec[j]; k++)
*it++ = j;
}
when I try to compile this with g++ and -std=c++11, -O3 flags I get the following error messages: 当我尝试使用g ++和-std = c ++ 11进行编译时,-O3标志会出现以下错误消息:
bucketSort.cpp:14:17: error: variable or field 'bucketSort' declared void
bucketSort.cpp:14:17: error: 'forwardIterator' was not declared in this scope
bucketSort.cpp:14:40: error: 'forwardIterator' was not declared in this scope
bucketSort.cpp: in function 'int main()':
bucketSort.cpp:55:46: error: 'bucketSort' was not declared in this scope
I don't understand what I'm doing wrong and how to fix this so that it works. 我不知道我在做什么错以及如何解决此问题以使其正常工作。
std::iterator_traits
can help you determine the value type given an iterator type. std::iterator_traits
可以帮助您确定给定迭代器类型的值类型。
template<typename forwardIterator>
void bucketSort(forwardIterator begin, forwardIterator end) {
using T = typename std::iterator_traits<forwardIterator>::value_type;
std::vector<unsigned> bucketVec(std::numeric_limits<T>::max() + 1, 0);
for (auto it = begin; it != end; it++)
bucketVec[*it]++;
auto it = begin;
for (unsigned j = 0; j < bucketVec.size(); j++)
for (unsigned k = 0; k < bucketVec[j]; k++)
*it++ = j;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.