Ahx
Ahx

Reputation: 7995

c++ Fast Way to Store txt values into vector<int>

I want to store my text values into my int vector, using c++.

My text values are: 250 251 251 252 ......

If my text values are char (e.g.) afv atd agg .....

Then I would use

vector<std::string> arr;
std::string path = "C:\\myText.txt";
glob(path,arr,false);

But for integer values inside text file, above code is not possible to implement.

Therefore I implemented following code:

vector<int> arr;
ifstream stream("C:\\myText.txt");
int num;
while(getline(stream,line)){
    istringstream(line) >> num;
    arr.push_back(num);
}

My question is: is there any faster way for implementing above code?

Something like using glob method for integer implementation?

Upvotes: 0

Views: 113

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

My text values are: 250 251 251 252 ......

If my text values are char (e.g.) afv atd agg .....

You can omit the getline() and istringstream in both cases:

template<typename T> 
void glob(std::istream& is,std::vector<T>& arr) {
    T val;
    while(is >> val) {
        arr.push_back(num);
    }
}

Use it like:

ifstream stream("C:\\myText.txt"); // myText.txt contains all numbers like 250 251 251 ...
std::vector<int> v;
glob(stream,v);

or

ifstream stream("C:\\myText.txt"); // myText.txt contains all words like afv atd agg ...
std::vector<std::string> v;
glob(stream,v);

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180945

This might not be faster but it is fewer lines of code and does no rely on constructing a istringstream from a std::strign for every line. Since a vector can be constructed from a iterator range we can use a istream_iterator constructed from the ifstream object and a default constructed one to mark the end of the file

std::ifstream fin("test.txt");
std::vector<int> data{ std::istream_iterator<int>(fin), std::istream_iterator<int>() };

This will read the integers from the file and insert them directly into the vector. I am not sure if this would be fewer memory allocations then using push_back.

Upvotes: 3

Related Questions