문제

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). The function is meant for T that's no bigger than short ints.

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:

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.

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top