有一个入门 C++ 类的编程项目 我们需要创建的函数之一是拆分函数



我希望得到一些反馈,了解我是否以"聪明的方式"这样做,或者我是否可以做得更快。 如果我在空白处拆分我可能会使用getline(stringstream,word,delimiter)但是我不知道如何将分隔符适应所有好字符,所以我只是遍历整个字符串生成一个新单词,直到我到达一个坏字符,但由于我对编程相当陌生,我不确定这是否是最好的方法。感谢您的任何反馈

            #include <iostream>
            #include <string> 
            using std::string;
            #include <vector> 
            using std::vector;
            #include <sstream>
            #include <algorithm>
            #include <iterator> //delete l8r
            using std::cout; using std::cin; using std::endl;
            /*
            void split(string line, vector<string>&words, string good_chars)
            o
            Find words in the line that consist of good_chars. 
            Any other character is considered a separator. 
            o
            Once you have a word, convert all the characters to lower case.
            You then push each word onto the reference vector words.
            Important: split goes  in  its  own  file.  This  is  both  for  your  own  benefit,  you  can  reuse 
            split, and for grading purposes.We will provide a split.h for you.
            */
            void split(string line, vector<string> & words, string good_chars){
                string good_word;
                for(auto c : line){
                    if(good_chars.find(c)!=string::npos){
                        good_word.push_back(c);
                    }
                    else{
                        if(good_word.size()){
                            std::transform(good_word.begin(), good_word.end(), good_word.begin(), ::tolower);
                            words.push_back(good_word);
                        }
                        good_word = "";
                    }
                }
            }
            int main(){
                vector<string> words;
                string good_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'";
                // TEST split
                split("This isn't a TEST.", words, good_chars);
                // words should have: {"this", "isn't", "a", "test"}, no period in test
                std::copy(words.begin(), words.end(), std::ostream_iterator<string>(cout, ","));
                cout << endl;
                return 0;
            }

我想说,考虑到C++类介绍的上下文,这是一种合理的方法。我什至会说,这很可能是你的导师期望看到的方法。

当然,可以进行一些优化调整。就像实例化一个 256 个元素的 bool 数组,使用 good_chars 将相应的值设置为 true ,而所有其他值默认为 false ,然后将find()调用替换为快速数组查找。

但是,我会预先指出,如果你交出这样的东西,你会被怀疑抄袭你在管间找到的东西,所以不要管它。

您可以考虑做的一件事是在push_back每个字符时使用tolower,并删除单词上多余的std::transform传递。

最新更新