C++:从向量中获取值

C++: Get value from a vector

本文关键字:获取 向量 C++      更新时间:2023-10-16

我有一个函数,可以将指针传递给一个无符号字符的向量。

有人能告诉我如何获得函数中的一个值吗?

double CApp::GetCost(unsigned char *uBytes)
{
   unsigned char iHP;
   iHP=uBytes[49]; //this does not work
}

编辑:对不起,我最初认为我应该简化代码,但我认为太多可能会出错。现在是真正的声明:

// ---------------------------------------
struct ByteFeature
{
    unsigned char Features[52];
};
class clsByteFeatures : public CBaseStructure
{
private:
   vector<ByteFeature> m_content;
protected:
   virtual void ProcessTxtLine(string line);
public:
   vector<ByteFeature> &Content();
   void Add(ByteFeature &bf);
};
vector<ByteFeature> &clsByteFeatures::Content()
{
   return m_content;
}

这就是我使用它的方式:

dblTargetCost  = GetCost(m_ByteFeatures.Content()[iUnitID].Features);

另一个问题:像这样简单地传递向量会不好吗?

double CApp::GetCost(vector<unsigned char> &uBytes)
{
  //...
}
Would it be bad to simply pass the vector like this?
double CApp::GetCost(vector<unsigned char> &uBytes)

不是,这是通过引用传递它的更好方法。但是,如果不希望修改uBytes,则可能需要添加const限定符。

double CApp::GetCost(const vector<unsigned char> &uBytes)
{
   try
   {
     unsigned char iHP = uBytes.at(49);
     //... 
   }
   catch(std::exception& e)
   {
     // process e
   }
   //...
}

编辑:

在你发布新帖子后,我觉得你只需要返回对m_content元素的引用,然后将引用传递给GetCost函数

ByteFeature& clsByteFeatures::operator[](int i) { return m_content.at(i); }

double GetCost(const ByteFeature& bf)
{
    std::cout << bf.Features[49]; << std::endl;
    return 0.0;
}

然后你打电话:

GetCost(m_ByteFeatures[iUnitID]);