指针:在 c++ 中不可分配的表达式
Pointers: Expression not assignable in c++
#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;
这就解决了。
相关文章:
- 对于结构,表达式必须是可修改的ivalue
- 表达式必须是可修改的左值.科迪米
- 我可以为unordered_map分配特定的模组值吗?
- 在线程中使用堆可分配 >100MB 的 RAM
- 哪种类型特征表明该类型是可分配的?(元组,对)
- C++概念相同且可分配
- 将值分配给指针时:表达式必须是可修改的lvalue
- Boost::spirit 无法识别可选表达式
- 是多个分配表达式(a = 123,b = 456,c = 789)
- 如何使具有包含唯一指针的成员变量的类可复制可分配
- GCC C++11 删除移动可分配类的副本分配会阻止 std::sort 编译
- 可视C++表达式必须具有常量值
- 如何使具有常量属性的类可分配
- 创建可分配的最大字符数组
- 如何使我自己的容器索引和可分配
- 为Fortran可分配程序在C中分配内存
- 移动包含向量<unique_ptr的可分配类<T>>
- Boost Spirit Parser可选表达式评估
- 移动clang和gcc中可分配的lambda
- 对左值和右值的可分配引用