Ben*_*oit 7 language-agnostic algorithm optimization implementation
假设我们有一个包含n个元素的数组(n> 0).
我们想输出这些元素的列表,它们之间有一个分隔符.
解决此问题的常见方法是:
foreach item
(
output item
output separator
)
trim last separator
Run Code Online (Sandbox Code Playgroud)
但是要做到这一点似乎有点混乱.
另一种方法是:
check that there is at least one element
loop
(
output element
next element, or break if no more elements
output separator
)
Run Code Online (Sandbox Code Playgroud)
但我不确定它是否会一直有效.
您是否看到其他聪明的方法,例如在C,C++中?
Ben*_*son 16
char *sep = "";
for (i = 0; i < size; ++i) {
printf("%s%s", sep, item[i]);
sep = ", ";
}
Run Code Online (Sandbox Code Playgroud)
lij*_*jie 11
for (i = 0; i < n; ++i) switch(i) {
default: output_separator();
case 0: output_item(i);
}
Run Code Online (Sandbox Code Playgroud)
或变化.我真的想不出还有什么不重复的output_item(i).
有时:
output item 0
for item 1 to n
{
output separator
output item
}
Run Code Online (Sandbox Code Playgroud)
更短.
由于它被标记为与语言无关,我认为重要的是要指出,有些语言具有内置功能,可以让您免于思考这个问题.以这个python代码为例:
>>> print string.join(['list', 'of', 'some', 'words'], ', ')
list, of, some, words
Run Code Online (Sandbox Code Playgroud)
一个可能的C++解决方案:
http://groups.google.com/group/comp.lang.c++/msg/a746a588cedfa44b
总结:写一个infix_ostream_iterator,基本上是相同的,ostream_iterator除了"separator"参数确实是一个分隔符,而不是每个项目的后缀.用法将是:
std::copy(first, last, infix_ostream_iterator<ItemType>(output, separator));
Run Code Online (Sandbox Code Playgroud)
无论好坏,我使用计数循环
for (i = 0; i < num_items; i++){
if (i > 0) output separator;
output item[i];
}
Run Code Online (Sandbox Code Playgroud)
我确信这是老式的诱饵,但它确实有效.
如果有人想告诉我它效率低下,男孩我准备好了火焰;-)