如何永久删除矢量的成员
How to permanently delete a member of a vector?
请允许我具体说明我的意思。假设我有以下代码:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector <int> ints;
ints.push_back(1);
ints.push_back(2);
ints.push_back(3);
for(int i=0;i<ints.size();i++) {
cout << ints[i] << endl;
}
cout << endl;
ints.erase(ints.begin());
for(int i=0;i<ints.size();i++) {
cout << ints[i] << endl;
}
return 0;
}
我该怎么做才能使该程序的版本在第一次运行时以已删除1
开头?基本上,2
第二次运行时将向量的开头,然后3
,然后在运行一定次数后基本上删除向量的每个元素。我是一个初学者程序员,如果这个解释不清楚,我很抱歉。
使用文件。您可以从文件中加载矢量的内容,将其打印出来,擦除第一个元素,然后将矢量的内容写回文件。如果打开文件进行读取失败,您可以假设这是程序第一次运行,并用初始值填充向量。
#include <fstream>
#include <iostream>
#include <vector>
std::vector<int> load(char const* filename)
{
// try to open the file for reading
std::ifstream fin(filename);
// couldn't open the file, so generate initial content
if (!fin) {
return { 1, 2, 3 };
}
// read the contents of the file into a vector, then return it
int x;
std::vector<int> v;
while (fin >> x)
v.push_back(x);
return v;
}
void save(char const* filename, std::vector<int> const& v)
{
std::ofstream fout(filename);
// put a 'n' between each number so that distinct numbers aren't
// concatenated together. e.g. Three seperate numbers 1, 2 and 3
// aren't combined to become a single number, 123
for (auto x : v)
fout << x << 'n';
}
int main(int argc, char* argv[])
{
char const* filename = "something";
auto v = load(filename);
for (auto x : v)
std::cout << x << 'n';
if (!v.empty())
v.erase(v.begin());
save(filename, v);
}
您有几个选择:
-
在运行时重写代码。这太疯狂了。更改已编译程序的二进制文件并不容易。
-
将矢量存储在外部文件中。您可以使用
std::cin
和一些删除器进行一些基本解析;试试这个例子,在这里:http://coliru.stacked-crooked.com/a/9a4d7a1a3f525b7e
我真的想不出更多了。但是每次运行时重写程序本身并不完全是C++允许的 - 做这样的事情更类似于病毒或即时编译器的行为,两者都需要自由地保护系统的安全性,并且可能不值得只是在每次程序运行时更改std::vector<int>
起始编号的值。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 类函数不会永久更改成员变量
- 指向成员函数的指针与指向数据成员的指针有何不同
- 在 for 循环中使用 push_front 不会将成员永久添加到列表中
- 如何永久删除矢量的成员