我需要获取数组中的字符数.
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
Run Code Online (Sandbox Code Playgroud)
我的任务很简单,因为数组没有重复的字符(例如,它不能像这样:{'a','1','f','a'}).我该怎么做?
seh*_*ehe 15
多一点C++:
#include <algorithm>
int getposition(const char *array, size_t size, char c)
{
const char* end = array + size;
const char* match = std::find(array, end, c);
return (end == match)? -1 : (match-array);
}
Run Code Online (Sandbox Code Playgroud)
更多C++:
template <typename T, size_t N>
int getposition(const T (&array)[N], const T c)
{
const T* match = std::find(array, array+N, c);
return (array+N==match)? -1 : std::distance(array, match);
}
Run Code Online (Sandbox Code Playgroud)
#include <algorithm>
#include <iterator>
template <typename Range, typename T>
size_t index_of(Range const& range, T const& c) {
using std::begin;
using std::end;
auto b = begin(range), e = end(range);
auto match = std::find(b, e, c);
return (e==match)? -1 : std::distance(b, match);
}
Run Code Online (Sandbox Code Playgroud)
在这里,原始问题得到直接支持std::string_view:
#include <string_view>
using namespace std::string_view_literals;
int main() {
return "hello"sv.find('e');
}
Run Code Online (Sandbox Code Playgroud)
#include <algorithm>
template <typename T, size_t size>
int getposition(T const (&array)[size], T const & c)
{
T const * found = std::find(&array[0], &array[size], c);
return found == &array[size] ? -1 : found - array;
}
Run Code Online (Sandbox Code Playgroud)
您需要告诉getposition()方法在数组中搜索多少元素,并且在编译时初始化数组,您可以使用该sizeof指令:
int number = getposition(myarray, sizeof(myarray), 'f');
...
int getposition(const char *array, size_t size, char c)
{
for (size_t i = 0; i < size; i++)
{
if (array[i] == c)
return (int)i;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35616 次 |
| 最近记录: |