Posts tagged c++
C++ Quickies #I : Long live the STL
0Its been quite some time (16+ months) I’ve been out of college and started using STL. Trust me, I didn’t know much about STL in college, though I used std::string & std::vector everywhere I could. Now, it seems like I couldn’t (wouldn’t ? ) write a program without using STL at all. A few snippets that I really found useful (and simple) and I regularly use where ever possible.
To output the elements (all / subset) in a container (lets say vector), separated by a delimiter, say new line:
#include <algorithm> std::copy(v.begin(), v.end(), std::ostream_iterator(std::cout, "\n"));
Want to sort an array? No problem …
#include <algorithm> std::sort(array, array + lengthOfArray);
Read from the standard input into a vector until the end-of-stream?
#include <algorithm> #include <iterator> #include <vector> typedef std::istream_iterator<int> istream_iterator_int; std::vector<int> v; istream_iterator_int start (std::cin); istream_iterator_int end; std::back_insert_iterator<vector<int> > dest (v); std::copy (start, end, dest);
Count the no. of instances an object is found?
#include <algorithm> size_t count = std::count(v.begin(), v.end(), 42); // Returns no. of elements in v with value 42.
And let me inform you… This is just a grain of what STL can do….
References:
I had a problem
0Symptoms:
- Language: C++, Operating System: Windows
- Target Audience: Programmers
- Sub Area: Reading ASCII / UTF-8 files from the disk using C++ streams.
- Trouble: How to handle files whose file names contains non-ASCII characters?? (coz ifstream takes a ASCII file path
)
Solution:
- Use _wfopen_s(), the safe version of _wfopen(), which takes a wide-character file name & gives a FILE pointer i.e; FILE*.
- Use the obtained FILE* to create a stream, like ifstream in(fp);
- We used wide-character file name & are reading the file byte-by-byte (actually, its char). DONE !!
BTW, I got help from here ! Hope this savesĀ time for someone out there…