指针:表达式不能在c ++中赋值

时间:2017-01-26 19:28:35

标签: c++ pointers

#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我想得到该值)并将其分配给另一个位置。

错误是:insertion.cpp:19:9:错误:表达式不可分配                         * j-1 = * j; //交换

我很确定我的困惑源于我对指针的理解不足,所以任何提示都值得赞赏

起初我用v [j-1] = v [j]等尝试过,所以直接在大括号中使用迭代器,但这也不起作用。

1 个答案:

答案 0 :(得分:2)

您有预测错误。

*(j-1) = *j;

修正了它。