列表<string>中的插入和删除

时间:2018-06-17 00:34:48

标签: c++ c++11 visual-c++

我目前正在编写一个小程序来插入或删除从输入文本文件中读取的字符串列表中的行。

这是我的代码

os.system("afplay path/to/sound/file.wav")

缓冲区列表有

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <list>

using namespace std;
int main()
{
    list <string> buffer;
    string fileName = "input.txt";
    ifstream file(fileName);
    if (file.is_open())
    {
        string line;
        while (getline(file, line))
        {
            //store each line in the buffer
            buffer.push_back(line);
        }
    }
    list<string>::const_iterator it;
    it = buffer.begin();
    int position = 1;
    for (int n = 0; n < position; ++n)
    {
        ++it;
    }
    string input("This is a new line");
    buffer.insert(it, 1, input);
    //I can then use erase function to delete a line

    system("pause");
    return 0;
}

我想知道是否有其他方法(可能更有效)在缓冲区中插入或删除一行。谢谢!

1 个答案:

答案 0 :(得分:0)

list<>::insert()有多个版本。其中一个插入一个元素,因此您可以替换它:

buffer.insert(it, 1, input);

使用:

buffer.insert(it, input);

您还可以使用list<>::emplace()来创建字符串:

buffer.emplace(it, "This is a new line");

你可以简化这个:

list<string>::const_iterator it;
it = buffer.begin();
int position = 1;
for (int n = 0; n < position; ++n)
{
    ++it;
}

为:

auto it = buffer.begin();
advance(it, 1);
相关问题