指针:在 c++ 中不可分配的表达式

Pointers: Expression not assignable in c++

本文关键字:可分配 表达式 不可分 c++ 指针      更新时间:2023-10-16
#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 中,我想获取值)并将其分配给另一个位置。

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

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

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

您有一个发生率错误。

*(j-1) = *j;

这就解决了。