从字母构建单词的最佳方法

时间:2015-01-29 14:00:23

标签: c++

我需要通过单独挑选字母来构建字母表中的单词。这样做的最佳方法是什么(最好的意思是最快)?目前我这样做:

string alpha = " abcdefghijklmnopqrstuvwxyz";
string word;
word = alpha.substr(9,1) + alpha.substr(6,1) + alpha.substr(13,1) + alpha.substr(13,1) + alpha.substr(16,1) + alpha.substr(1,1) + alpha.substr(1,1);

拼写"你好"然后我用以下内容删除可能的空格:

word.erase(remove_if( word.begin(), word.end(), ::isspace), word.end() );

我是c ++的新手,更多是c#背景。这是一个很好的方法吗?或者我应该使用char []?甚至可能是机器代表?这不可能是最好的方法,因为c#中List上的简单foreach循环执行得更快......

3 个答案:

答案 0 :(得分:3)

  

这样做的最佳方式是什么(最好的意思是最快)?

这可能是最快的:

  • 为您想要的所有字母保留足够的空间;
  • 选择单个字符(不是长度为1的子字符串)并附加这些字符。

看起来像

string word;
word.reserve(7);
word += alpha[9];
// ...
word += alpha[1];

这最多只涉及一次内存分配。您的方法会创建多个中间string对象,这些对象可能会或可能不会涉及更多分配,具体取决于string的实现方式。

与优化时一样,进行衡量以确保您的工作是值得的优化。

  

或者我应该使用char[]

如果在编译时已知大小(或至少是上限),那么这将允许您完全避免动态分配。如果不是,那么你就不能。

您可以以类似的方式删除空格;由于数组大小是固定的,因此您需要跟踪有效数据的结束:

char word[MAX_SIZE];       // enough space for MAX_SIZE
char * end = word + size;  // "size" is the actual number of valid characters

// Remove spaces from the range [word,end)
// and update end to point to the end of the remaining letters
end = remove_if(word, end, ::isspace);

答案 1 :(得分:2)

在这种情况下,最快的可能是

string alpha = " abcdefghijklmnopqrstuvwxyz";
string word {alpha[9], alpha[5], alpha[13], alpha[13], alpha[16], alpha[0], alpha[0]};

也就是说:直接将单词构造为正确长度的字符串,只选择你需要的字符。

遗憾的是,删除某些可能出现多次的char的快速方法并不简单,您需要自己编写代码:

std::string copy;
copy.reserve(word.size()); // Somewhat too much, but OK
for (char c: word) if (c!= ' ') copy.append(c);

int j = 0;
for (int i = 0; i != word.size(); ++i)
  if(word[i] != ' ') word[j++] = word[i];
word.resize(j);

答案 2 :(得分:0)

要获得单个字母,您需要字母[9],而不是alphabet.substr(9,1) 因为前者收到那封信 然后构造一个新字符串并将该字母复制到其中。