C ++:数组中的元素炭获取指数 [英] C++: Get index of char element in array

查看:124
本文介绍了C ++:数组中的元素炭获取指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在阵列字符数。

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

我的任务是容易的,因为阵列不必重复字符(例如,它不能是不服这样:{'一','1','F','一个'})。我该怎么办呢?

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?

推荐答案

一点点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);
 }

还有很多C ++:

A lot more 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 (end==match)? -1 : std::distance(array, match);
 }

这篇关于C ++:数组中的元素炭获取指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆