C ++获取向量中const char * []的长度

时间:2018-09-07 15:30:21

标签: c++ vector const-char

如何获取const char *数组索引的长度?

向量:

std::vector<const char*> _infoBarText;

const char * []:

const char* text[4] = {"Current T:", "Target T:", "Time elapsed:", "Time remaining:"};

将char数组分配给向量:

_infoBarText.assign(text, text+4);

如何从向量中获取各个字符串的长度,例如"current T"

2 个答案:

答案 0 :(得分:7)

原始C字符串(裸char*-s)不适合现代C++代码。

如果将其更改为std::vector<std::string_view>,就可以解决您的问题而几乎(几乎)没有任何开销(假设您使用文字对其进行了初始化),并且作为奖励,您有可能使它更安全,更实用。

有关详细信息,请参见cppreference article

示例(GodBolt):

#include <string_view>
#include <vector>
#include <iostream>

int main() {
    using namespace std::literals;

    std::vector<std::string_view> strs = { "hello"sv, "there"sv };

    for (auto&& str: strs)
        std::cout << str << str.size();

    return 0;
}

GodBolt Code Insight输出(请注意std::operator""sv("hello", 5ul)):

#include <string_view>
#include <vector>
#include <iostream>

int main()
{
  using namespace std::literals;
  std::vector<std::string_view> strs = std::vector<std::basic_string_view<char, std::char_traits<char> >, std::allocator<std::basic_string_view<char, std::char_traits<char> > > >{std::initializer_list<std::basic_string_view<char, std::char_traits<char> > >{std::operator""sv("hello", 5ul), std::operator""sv("there", 5ul)}, std::allocator<std::basic_string_view<char, std::char_traits<char> > >()};
  {
    std::vector<std::basic_string_view<char, std::char_traits<char> >, std::allocator<std::basic_string_view<char, std::char_traits<char> > > > & __range = strs;
    __gnu_cxx::__normal_iterator<std::basic_string_view<char, std::char_traits<char> > *, std::vector<std::basic_string_view<char, std::char_traits<char> >, std::allocator<std::basic_string_view<char, std::char_traits<char> > > > > __begin = __range.begin();
    __gnu_cxx::__normal_iterator<std::basic_string_view<char, std::char_traits<char> > *, std::vector<std::basic_string_view<char, std::char_traits<char> >, std::allocator<std::basic_string_view<char, std::char_traits<char> > > > > __end = __range.end();

    for( ; __gnu_cxx::operator!=(__begin, __end); __begin.operator++() )
    {
      std::basic_string_view<char, std::char_traits<char> > & str = __begin.operator*();
      std::operator<<(std::cout, std::basic_string_view<char, std::char_traits<char> >(str)).operator<<(str.size());
    }
  }
  return 0;
}

答案 1 :(得分:2)

很长的路要走

#include <vector>
#include <cstring> // for strlen

std::vector<const char*> _infoBarText;
char const *str = _infoBarText[0]; // or any other valid index
auto len = std::strlen(str);

简短:

auto len = std::strlen(_infoBarText[0]);