【问题标题】:Insert() in uint8_t array在 uint8_t 数组中插入()
【发布时间】:2021-03-20 07:24:58
【问题描述】:

我是 C++ 新手,当我尝试在 uint8_t 数组中插入一个元素时,我收到以下错误。请帮我解决这个问题。

错误

main.cpp: In function ‘int main()’:

main.cpp:10:9: error: request for member ‘insert’ in ‘array’, which is of non-class type ‘uint8_t [5] {aka unsigned char [5]}’
   array.insert(1,0xff);

代码是

#include <iostream>

#include <string.h>

using namespace std;

int main ()
{
  
  uint8_t array[] = {0x00, 0x11,0x22,0x33,0x44};
  
  array.insert(1,0xff);
  
  for(int i=0; i<6; i++){

      cout << array[i]<< " ";

  }

  return 0;

}

我希望输出数组是

array[] = {0x00, 0xff, 0x11,0x22,0x33,0x44};

【问题讨论】:

  • 注意:#include &lt;string.h&gt; 在这里不相关,甚至不属于大多数 C++ 程序。

标签: c++ arrays string


【解决方案1】:

这不是 insert 可以使用的东西,像 uint8_t 这样的原始类型没有函数。这就是“非类类型”的意思。

你需要std::vector&lt;uint8_t&gt;,它确实有insert()。来自#include &lt;vector&gt;

要记住的一点是,如果您不关心索引,C++ 有一个快速简单的迭代器方法可以使用:

for (auto&& e : array) {
  cout << e << " ";
}

超级简单!

把这一切放在一起:

#include <iostream>
#include <vector>

// Tip: Avoid using namespace std, the std:: prefix exists for a reason

int main ()
{
  std::vector<uint8_t> array = {0x00, 0x11,0x22,0x33,0x44};
  
  array.insert(array.begin() + 1, 0xff);
  
  for (auto&& e : array) {
    std::cout << e << " ";
  }

  std::cout << std::endl;

  return 0;
}

【讨论】:

  • 我能知道如何将 uint8_t 数组 [] 复制到 std::vector 吗?
  • 改用std::vectorstd::vector&lt;uint8_t&gt; array = {0x00, 0x11,0x22,0x33,0x44};
  • 这给了我一组错误 main.cpp:14:3: error: 'vector' is not a member of 'std' std::vector array = {0x00, 0x11 ,0x22,0x33,0x44}; ^~~ main.cpp:14:22: 错误: '>' 标记之前的预期主表达式 std::vector array = {0x00, 0x11,0x22,0x33,0x44}; ^ main.cpp:14:24: 错误:'array' 未在此范围内声明 std::vector array = {0x00, 0x11,0x22,0x33,0x44};
  • 你有#include &lt;vector&gt; 吗?
  • 感谢评论#include 。错误现已解决。你能用问题的向量自己写一个答案吗,因为这会给我一个明确的问题解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
相关资源
最近更新 更多