将一个数组归因于另一个数组的困难
Difficulties on atributting a array to another
当我尝试使用char[20] array
并将其"内容"放入另一个相同大小的数组中时,我遇到了问题。
struct book{
char author[20];
char title[20];
};
book library [100];
void removebook(){
for (cont; cont<=quantidade; cont++){
cont2=(cont+1);
// HERE is where all goes downhill ↓↓↓↓↓↓↓↓↓↓↓
library[cont].author = library[cont2].author
}
我得到的错误是[Error] invalid array assignment
目的是在library[4].author
上写一个作者的名字来覆盖library[3].author
喜欢:
library[4].author=Mark;
library[3].author = library[4].author;
现在library[3].author
上的任何内容都被mark
不能复制带有operator=
的数组。您可以使用新式C++
#include <array>
#include <cstddef>
// #include <list>
#include <string>
// #include <vector>
struct book{
std::string author;
std::string title;
};
std::array<book, 100> library; // or std::vector<book> library;
// or std::list<book> library;
void removebook(std::size_t idx) {
for (std::size_t cont = idx; cont < library.size() - 1; ++cont){
std::size_t cont2 = cont + 1;
library[cont] = library[cont2];
}
}
也许你可以用 std::remove 等算法中的函数或 std::vector::erase 或 std::list::erase 等方法替换removebook
主体,具体取决于您的实现方式,例如用于std::array<book, 100> library
#include <array>
#include <cstddef>
#include <string>
struct book{
std::string author;
std::string title;
};
std::array<book, 100> library;
void removebook(std::size_t idx) {
std::copy(library.begin() + idx + 1, library.end(), library.begin() + idx);
library.back() = book{};
}
当您的属性定义为传统的 C 字符数组时,两个传统 C 字符数组之间的=
运算符将尝试将右侧第一个数组地址分配给左侧参数library[cont].author
因为实际上在内存中包含常量 char 地址。
该行:
library[cont].author = library[cont2].author;
实际上尝试获取library[cont2].author
值,即常量字符地址,并将其分配给library[cont].author
该值也是常量字符地址(导致失败(。即使它能工作,它也不会做你想要它做的事情。
存档如果它有效时会做什么的最接近方法是将author
定义为char*
.假设我们在library
的每个成员中为此属性分配了一个内存。同一行代码将使所有指针包含相同的内存地址,现在您可以看到它会造成多少麻烦。
解决方案可以std::string
@ThomasSablik答案中提到的或@Peterstd::array<char, 20>
中提到的
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- C++未知长度字符串的数组,其行为类似于 Python 字符串列表
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 适用于大型数组的无复制线程安全环形缓冲区
- C++中用于结构的纯数组的类似于TableView/DataFrame的通用功能
- 将一个数组归因于另一个数组的困难
- 为什么std::begin()和std::end()适用于固定数组,而不适用于动态数组
- 通过矢量下标访问 Fortran 数组,相当于 cpp
- 使用不同的整数组装字符数组以类似于日期和时间
- 如何在C 中创建类似于Python的Numpy数组的数组
- 如何将单独的数组分组在一起(类似于按一列对表进行排序)
- 将二进制操作员应用于数组中的每个元素
- 最小的正乘数,当应用于数组时,使数组成为积分
- C++相当于 Python 的:用于数组索引
- C# 是否有办法将双精度数组强制转换为类似于C++转换为 char* 的字符串?
- C++ ->尝试逐字阅读一行文本。如何使指针等效于用于存储输入的当前二维数组
- 将相同的功能应用于不同大小的N数组的每个元素
- C 中的数组中的数组类似于Python中的内部列表
- 枚举数组相对于常量和宏的优势
- 数组相对于向量有什么优势?