簡體   English   中英

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

[英]Insertion and Deletion in list <string>

我目前正在編寫一個小程序,以在從輸入文本文件讀取的字符串列表中插入或刪除行。

這是我的代碼

#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;
}

緩沖區列表有

This is line 1
This is line 2
This is line 3
This is line 4

我想知道是否還有其他方法(可能更有效)在緩沖區中插入或刪除一行。 謝謝!

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM