Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:13

0001 // name=LongestCommonPrefixTest ; gcc $name.cc -std=c++11 -lstdc++ -o /tmp/$name && /tmp/$name
0002 
0003 #include <algorithm>
0004 #include <iostream>
0005 #include <vector>
0006 #include <string>
0007 
0008 /**
0009 translation from the python os.path.commonprefix 
0010 **/
0011 
0012 std::string commonprefix(const std::vector<std::string>& a)
0013 {
0014     std::vector<std::string> aa(a); 
0015     std::sort( aa.begin(), aa.end() ); 
0016     const std::string& s1 = aa[0] ; 
0017     const std::string& s2 = aa[aa.size()-1] ; 
0018     for(unsigned i=0 ; i < s1.size() ; i++) if( s1[i] != s2[i] ) return s1.substr(0,i) ; 
0019     return s1 ; 
0020 } 
0021 
0022 void dump(const std::vector<std::string>& a)
0023 {
0024     std::cout << "-----" << std::endl ; 
0025     for(unsigned i=0 ; i < a.size() ; i++ ) std::cout << a[i] << std::endl; 
0026 }
0027 
0028 
0029 int main()
0030 {
0031     std::vector<std::string> a = { "one/z", "one/a", "one/b", "one/c" } ; 
0032     dump(a); 
0033 
0034     std::string cpfx = commonprefix(a); 
0035     std::cout << " cpfx " << cpfx << std::endl ; 
0036 
0037     dump(a); 
0038 
0039 
0040     return 0 ; 
0041 }