C++:获取数组中 char 元素的索引
我需要获取数组中的字符数。
const char myarray[5] = {'0', 'a', 'e', 'f', 'c'}; // Create array of char
int number=0; // Create variable
number = getposition(myarray, 'f'); // Now number equals to 3
number = getposition(myarray, 'z'); // -1, because array doesn't have this char
我的任务很简单,因为数组没有重复字符(例如,它不能像这样:{'a', '1', 'f', 'a'})。我该怎么做呢?
I need to get number of character in array.
const char myarray[5] = {'0', 'a', 'e', 'f', 'c'}; // Create array of char
int number=0; // Create variable
number = getposition(myarray, 'f'); // Now number equals to 3
number = getposition(myarray, 'z'); // -1, because array doesn't have this char
My task is easy because array don't have repeating characters (for example, it can't be smth like this: {'a', '1', 'f', 'a'}). How can I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
多一点 C++:
多一点 C++:
额外的 C++11/C++11 更新
额外的 C++17 更新
在这里,原始问题在
std::string_view
中得到直接支持:<强>直播科利鲁
A little bit more C++:
A lot more C++:
Bonus C++11/C++11 update
Bonus C++17 update
Here, the original question gets direct support in
std::string_view
:Live On Coliru
您需要告诉
getposition()
方法要在数组中搜索多少个元素,并且当数组在编译时初始化时,您可以使用sizeof
指令:You need to tell the
getposition()
method how many elements to search within the array and as the array is initialised at compile time you can use thesizeof
directive:如果这确实是一个纯粹的解码练习 - 为什么不重新组织你的数组......那么查找是恒定时间 - 例如。
所以现在你的查找函数是:
你很难在性能上击败它......
If this really is a pure decoding exercise - why not re-organize your array... then lookup is constant time - e.g..
so now your look up function is:
You'd be hard-pressed to beat that for performance...
您还需要将数组大小传递给函数。
You need to pass the array size as well to the function.