If you want to search multiple times I suggest putting the file content into a hash table. This gives you O(1) lookup which is optimal.
fastest way to convert a file to list c++
-
10-07-2023 - |
Вопрос
i have a file full of integers, sorted, i need to get the content of the file to a list. the file looks something like this:
1
4
45
150
245
365
i know it's possible to read line by line and push_back, but the file count more than 500 000 line so is their a quick way to do this?
the goal is to see if an integer is in the file, so i need to convert to list and then do a binary_search, if you have a better idea, i'll be gratefull.
Решение 2
Другие советы
To read into list you can use std::istreambuf_iterator
:
std::ifstream t( "file.txt");
std::list<int> l( ( std::istreambuf_iterator<int>( t)),
std::istreambuf_iterator<int>());
I would do this like:
#include <iostream>
#include <iterator>
#include <unordered_set>
int main() {
std::ifstream t { "file.txt", ios::ate };
std::unordered_set s;
s.reserve(t.tellg());
t.seekg(0);
s.insert(std::istream_iterator<int>(t), std::istream_iterator<int>());
// now you can use s.find(key) to see if something is in the set
}
Не связан с StackOverflow