gpt4 book ai didi

c++ - 指针:在 C++ 中不可赋值的表达式

转载 作者:行者123 更新时间:2023-11-28 01:54:00 24 4
gpt4 key购买 nike

#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 中,我试图为泛型编写一个插入排序函数。错误来 self 尝试“交换”的行。它应该在迭代器当前所在的 vector 中获取值(例如在索引 2 处我想获取值)并将其分配给另一个位置。

错误是:insertion.cpp:19:9: error: expression is not assignable *j-1 = *j;//交换

我很确定我的困惑源于我对指针的理解不足,所以欢迎任何提示

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

最佳答案

你有一个预测错误。

*(j-1) = *j;

那就解决了。

关于c++ - 指针:在 C++ 中不可赋值的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41881414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com