当输入值是一系列值, 而需要求对应的输出值时, 建议用本文要介绍的代码范式。啥也不说了, 直接撸代码:
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
void fun(vector<string> &v, map<string, int> &m)
{
vector<string>::iterator it;
int i = 0;
for(it = v.begin(); it != v.end(); ++it)
{
m[*it] = i++;
}
}
int main()
{
vector<string> v;
v.push_back("zhangsan");
v.push_back("lisi");
map<string, int> m;
fun(v, m);
map<string, int>::iterator it;
for(it = m.begin(); it != m.end(); ++it)
{
cout << it->first << " : " << it->second << endl;
}
return 0;
}
结果为:
taoge@localhost test> g++ test.cpp
taoge@localhost test> ./a.out
lisi : 1
zhangsan : 0
taoge@localhost test>
加上const更好, 变为:
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
void fun(const vector<string> &v, map<string, int> &m)
{
vector<string>::const_iterator it;
int i = 0;
for(it = v.begin(); it != v.end(); ++it)
{
m[*it] = i++;
}
}
int main()
{
vector<string> v;
v.push_back("zhangsan");
v.push_back("lisi");
map<string, int> m;
fun(v, m);
map<string, int>::iterator it;
for(it = m.begin(); it != m.end(); ++it)
{
cout << it->first << " : " << it->second << endl;
}
return 0;
}
结果还是一样。
但是, 如下两个代码都错误(如果没有看出错误, 请继续学习C++基础知识):
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
void fun(const vector<string> &v, map<string, int> &m)
{
vector<string>::iterator it; // error
int i = 0;
for(it = v.begin(); it != v.end(); ++it)
{
m[*it] = i++;
}
}
int main()
{
vector<string> v;
v.push_back("zhangsan");
v.push_back("lisi");
map<string, int> m;
fun(v, m);
map<string, int>::iterator it;
for(it = m.begin(); it != m.end(); ++it)
{
cout << it->first << " : " << it->second << endl;
}
return 0;
}
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
void fun(const vector<string> &v, map<string, int> &m)
{
const vector<string>::iterator it; // error
int i = 0;
for(it = v.begin(); it != v.end(); ++it)
{
m[*it] = i++;
}
}
int main()
{
vector<string> v;
v.push_back("zhangsan");
v.push_back("lisi");
map<string, int> m;
fun(v, m);
map<string, int>::iterator it;
for(it = m.begin(); it != m.end(); ++it)
{
cout << it->first << " : " << it->second << endl;
}
return 0;
}
OK, 不多说。