如果你的编译器支持一些 c++11 特性
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<std::string> > dictionary(26);
//'a' part
dictionary[0].push_back("alien");
dictionary[0].push_back("amend");
dictionary[0].push_back("apple");
//.......
//'z' part
dictionary[25].push_back("zero");
dictionary[25].push_back("zoo");
//sort all of the words after insert
for(auto &strs : dictionary){
std::sort(std::begin(strs), std::end(strs));
}
//find the specific words of 'a'
auto const it = std::equal_range(std::begin(dictionary[0]), std::end(dictionary[0]), "apple");
if(it.first != it.second){
std::cout<<*(it.first)<<std::endl;
}else{
std::cout<<"The word do not exist"<<std::endl;
}
return 0;
}
如果没有,那么代码会变得有点乏味
#include <algorithm>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<std::string> > dictionary(26);
//'a' part
dictionary[0].push_back("alien");
dictionary[0].push_back("amend");
dictionary[0].push_back("apple");
//.......
//'z' part
dictionary[25].push_back("zero");
dictionary[25].push_back("zoo");
//you could use std::for_each if you like, I choose for loop because I
//don't like to write so many trivial functor
typedef std::vector<std::vector<std::string> >::size_type size_type;
size_type const size = dictionary.size();
for(size_type i = 0; i != size; ++i){
std::sort(dictionary[i].begin(), dictionary[i].end());
}
//find the specific words of 'a'
typedef std::vector<std::string>::const_iterator StrIter;
std::pair<StrIter, StrIter> it = std::equal_range(dictionary[0].begin(), dictionary[0].end(), "apple");
if(it.first != it.second){
std::cout<<*(it.first)<<std::endl;
}else{
std::cout<<"The word do not exist"<<std::endl;
}
return 0;
}