如何永久删除矢量的成员

How to permanently delete a member of a vector?

本文关键字:成员 何永久 删除      更新时间:2023-10-16

请允许我具体说明我的意思。假设我有以下代码:

#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>起始编号的值。