How many people give up, because of YOU.
Continue...
先实践,最后需要总结。
1. 数据流中的数据按照一定的格式<T>提取 -------> 放在vector中。
2. 注意 vector.begin(), vector.front()的区别。
3. accumulate()求sum。(与valarrary貌似有一拼,孰优孰劣?---- 可能后者效率更高)
4. multiplies<int>() c++ --> reference --> <functional> --> multiplies
#include<math.h> #include<iostream> #include<fstream> #include<algorithm> #include<functional> #include<numeric> #include<vector> #include<iterator> // continue... int main() { std::vector<int> v; std::ifstream in("numbers.txt"); //Jeff --> //1. Input stream --> in, 迭代器 迭代出int from stream。 //2. Call default constructor, generate ‘eof‘. //3. Use back_inserter to call Container‘s member function. std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(), std::back_inserter(v)); for (unsigned int i = 0; i < v.size(); i++) { std::cout << v[i] << std::endl; } /**************************************************************************/ //Jeff --> sort on specific range. // begin: return iterator. std::sort(v.begin(), v.end()); //Jeff --> front: return &value. std::cout << "min/max: " << v.front() << " " << v.back() << std::endl; std::cout << "median: " << *(v.begin() + (v.size()/2)) << std::endl; std::cout << "average: " << accumulate(v.begin(), v.end(), 0.0) / v.size() << std::endl; std::cout << "geomean: " << std::pow( accumulate(v.begin(), v.end(), 1.0, std::multiplies<double>()), 1.0/v.size() ) << std::endl; }
字典map(key, value)的使用。
vector获得stream的数据,然后存在map中。
copy()作为输出的技巧:输出到vector中。
int test02(void) { using namespace std; std::vector<string> v; // map<key, value> std::map<string, int> m; std::ifstream in("words.txt"); std::copy(std::istream_iterator<string>(in), std::istream_iterator<string>(), std::back_inserter(v)); // The number of times it occurs in a file. for (auto vi = v.begin(); vi != v.end(); ++vi) ++m[*vi]; for (auto mi = m.begin(); mi != m.end(); ++mi) std::cout << mi->first << ": " << mi->second << std::endl; return 0; }
string也是一个contrainer。
copy()作为输入的技巧:拷贝到ostream。
int test03(void) { std::vector<int> v = {1, 3, 5, 4, 3, 2}; std::string s("string"); std::sort(v.begin(), v.end()); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ",")); std::cout << std::endl; std::sort(s.begin(), s.end()); std::copy(s.begin(), s.end(), std::ostream_iterator<char>(std::cout, " ")); std::cout << std::endl; return 0; }
Next:
In reality, not all operations are supported in all containers,
http://www.cplusplus.com/reference/stl/
需要逐个实践下,为下一节做准备
时间: 2024-10-25 22:31:00