将一个数组归因于另一个数组的困难

Difficulties on atributting a array to another

本文关键字:数组 归因于 另一个 一个      更新时间:2023-10-16

当我尝试使用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>中提到的