C/C++

Переставить в файле первую и последнею строку C++

Напиши пожалуйста код программы
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
int n;
string tmp;
vector<string>s(100);
const string fn = "file.txt";
ofstream ofs;
ifstream ifs;
ifs.open(fn);
if(ifs.is_open())
{
while(getline(ifs,tmp) && n < 100)
{
for(int y = 0; y < tmp.length(); y++) s[n].push_back(tmp[y]);
n++;
}
ofs.open(fn);
if(ofs.is_open())
{
ofs << s[n-1] << endl;
for(int x = 1; x < n - 1; x++)
ofs << s[x] << endl;
ofs << s[0] << endl;
ofs.close();
}
ifs.close();
}
return 0;
}
Ирек Баширов
Ирек Баширов
87 957
Лучший ответ
Андрей Галкин К чему такая жесть, строку посимвольно впихивать в вектор?
"Раз пошла такая пьянка"
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>

using namespace std;

struct line : public string { using string::string; };
istream& operator>>(istream& s, line& l) { getline(s, l); return s; }

int main() {
fstream file("test.txt");
vector<string> text((istream_iterator<line>(file)), istream_iterator<line>());
swap(text.front(), text.back());
file.clear(); file.seekp(0);
copy(text.begin(), text.end(), ostream_iterator<string>(file, "\n"));
}

https://onlinegdb.com/xhDwvYoiY

ЗЫЖ Да считаю с line лучше, в т.ч. позволило использовать конструктор у vector.
Проверки можно добавить. Не стал.
Пассаж с одним fstream и seekp все равно считаю лучше, чем использование второго объекта, хотя что там соптимизирует компилятор не смотрел. Тем более мы так сразу "просим" права rw.
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
ifstream file("N:/text.txt");
vector<string>file_str;
string str;
while (getline(file, str))
file_str.push_back(move(str));
swap(*file_str.begin(), *(file_str.end() - 1));
file.close();
bool first = false;
ofstream out("N:/text.txt");
for (auto& i : file_str) first ? out << "\n" << i: out << i,first=true;
}
Ирек Баширов move из sstream?
Виталий Трегубенков Он кажется во всех библиотеках есть
Влюбленый Мальчик file_str.emplace_back(move(str));
swap(file_str.front(), file_str.back()); // так
iter_swap(file_str.begin(), file_str.end() - 1); // или так