C++STL 算法中transform函数应该怎么使用,请大家帮忙看看

木兮₀₃₂₁ 2016-09-13 10:55:45
上代码:
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <iterator>
#include <algorithm>
#include <cctype>

using namespace std;
char toLower(char ch){return tolower(ch);}
string & ToLower(string &st);
void display(const string &s);

int main()
{
vector<string> words;
cout<<"Enter the words (enter quit to quit):\n";
string input;
while(cin>>input && input!="quit")
words.push_back(input);
cout<<"You enetered the following worlds:\n";
for_each(words.begin(), words.end(), display);
cout<<endl;
//将words 移到 set里面,并转化成小写
set<string>wordset;
transform(words.begin(), words.end(), wordset.begin(), ToLower);//这里第三个参数有问题
/*
template <class _InputIterator, class _OutputIterator, class _UnaryOperation>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
{
for (; __first != __last; ++__first, (void) ++__result)
*__result = __op(*__first);
return __result;
}

*/函数原型如下
cout<<"\nAlphabetic list of words: \n";
for_each(wordset.begin(), wordset.end(), display);
cout<<endl;

//将words 和出现次数 保存到map
map<string, int >wordmap;
set<string>::iterator si;
for (si=wordset.begin(); si!=wordset.end(); si++)
wordmap[*si]=(int)count(words.begin(), words.end(), *si);
//display map contents
cout<<"\nWord freqency:\n";
for (si=wordset.begin(); si!=wordset.end(); si++) {
cout<<*si<<" : "<<wordmap[*si]<<endl;
}
return 0;
}

string & ToLower(string &st)
{
transform(st.begin(), st.end(), st.begin(), toLower);
return st;
}
void display(const string &s)
{
cout<<s<<" ";
}


我想问的是,transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)第三个参数代表什么,为什么不能这样写?
...全文
678 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
微book 2016-09-17
  • 打赏
  • 举报
回复
set<string>wordset; ------------------------------- vector<string>wordset(words.begin(),words.end());
CodefansZ 2016-09-14
  • 打赏
  • 举报
回复
http://zh.cppreference.com/w/cpp/algorithm/transform 应该好好利用这个网站,其中的知识体系非常完善,例子也很丰富
paschen 版主 2016-09-14
  • 打赏
  • 举报
回复
第三个参数意思:the beginning of the destination range, may be equal to first1 or first2 具体静下心看完:http://en.cppreference.com/w/cpp/algorithm/transform
lm_whales 2016-09-14
  • 打赏
  • 举报
回复
这里有两个容器 第一,第二 两个参数,是第一个容器的输入迭代器,表示数据源的开始和结束位置。 第三个参数是另一个容器的输出迭代器。表示计算结果,开始存放。 这两个容器,如果相同的话,可能会出问题,使用的时候,需要谨慎。
zmyouren1983 2016-09-14
  • 打赏
  • 举报
回复
第1和2个参数是数据起始和结束位置(迭代器) 参数3是写入目标的起始位置 参数4是执行的操作(函数)

64,662

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧