#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では、ジェネリック型の挿入ソート関数を記述しようとしています。エラーは私が "スワップ"しようとする行から来ています。イテレータが現在あるベクトルの値を取ることになっています(たとえば、インデックス2で値を取得したいなど)、それを他の位置に割り当てます。ポインタ:式がC++で代入不可
エラーは次のとおりです。insertion.cpp:19:9:error:式が割り当てられません。 * j-1 = * j; //スワップ
私は私の混乱は、ポインタの私の理解不足に起因するので、任意のヒントが最初に
を高く評価している私は、V [J-1] = V [J]などでそれを試してみましたかなり確信していますそのため、イテレータは中括弧で直接使用していましたが、どちらもうまくいきませんでした。
あなたの混乱は、[C++の演算子の優先順位](http://en.cppreference.com/w/cpp/language/operator_precedence)を知らない/理解していないことから生じるようです。 – WhozCraig
さて、それを修正しました、ありがとうございます –
ここにコードを投稿すると、余分な空白行を最小限に抑えることをお勧めします。読者は、コードの関連部分を見るために、さらにスクロールする必要があります。 – crashmstr