2017-01-26 4 views
0
#include <iostream> 
#include <vector> 

using namespace std; 

template<typename T> 
void new_insertion_sort(std::vector<T> &v) 
{ 
    for(auto iter = v.begin(); iter != v.end(); ++iter) 
    { 
     auto j = iter; 
     std::cout << "1 "; 
     while(j > v.begin()) 
     { 
      if(*j > *j-1) // we do not want iterator here, but the value at that 
       {break;} 

      auto current = *j-1; // save for swap 
      *j-1 = *j; // swap 
      *j = current; // restore position before, without it the two adjacent would be the same 

      j--; 

     } 



    } 

} 


void insertion_sort(std::vector<double> &v) 
{ 
    for(int i = 0; i < v.size(); i++) 
    { 
     int j = i; 

     while(j > 0) 
     { 
      if(v[j] > v[j-1]) 
       {break;} 

      double current = v[j-1]; // save for swap 
      v[j-1] = v[j]; // swap 
      v[j] = current; // restore position before, without it the two adjacent would be the same 

      j--; 

     } 



    } 

} 

template<typename T> 
void print_vector(T v){ 

    for(auto &element: v) 
    { 
     std::cout << element << std::endl; 
    } 

} 

int main(int argc, char const *argv[]) 
{ 
    std::vector<double> v={5,4,3,2,7}; 
    std::vector<int> w={4,6,23,6,35,235,346,37,46}; 

    std::cout << " Dies ist der geordnete Vektor! " << std:: endl; 
    insertion_sort(v); 
    print_vector(v); 




    new_insertion_sort(v); 
    new_insertion_sort(w); 
    std::cout << " Dies ist der geordnete Vektor v ! " << std:: endl; 
    print_vector(v); 
    std::cout << " Dies ist der geordnete Vektor v ! " << std:: endl; 
    print_vector(w); 

    return 0; 
} 

첫 번째 함수 new_insertion_sort에서 제네릭 유형에 대한 삽입 정렬 함수를 작성하려고합니다. 오류는 "스왑"하려고하는 행에서 비롯됩니다. iterator가 현재있는 벡터에서 값을 가져 와야한다고 가정합니다 (예 : 인덱스 2에서 값을 가져 오려면). 다른 위치에 할당합니다.포인터 : C++에서 할당 할 수없는 표현식

오류 : insertion.cpp : 19 : 9 : 오류 : 표현식을 할당 할 수 없습니다. * j-1 = * j; // 스왑

내 혼란이 포인터의 내 이해 부족에서 비롯된 확신, 그래서 어떤 조언이 나는 v를 사용하여 그것을 시도 처음에는

을 부탁드립니다 [J-1] = V [J] 등 그래서 중괄호에서 직접 반복자를 사용하지만 그 중 하나는 작동하지 않습니다.

+1

지금 혼란은 [C++의 연산자 우선 순위] (http://en.cppreference.com/w/cpp/language/operator_precedence)를 모르거나 이해하지 못하는 것에서 비롯된 것 같습니다. – WhozCraig

+0

좋아요, 고쳐 주셔서 감사합니다. –

+0

여기에 코드를 게시하면 여분의 빈 줄을 최소한으로 유지하는 것이 좋습니다. 단지 독자가 코드의 관련 부분을보기 위해 더 많이 스크롤해야합니다. – crashmstr

답변

2

당신은 선행 오류가 있습니다.

*(j-1) = *j; 

수정했습니다.

+1

또는 :'j [-1] = j [0]' –

관련 문제