将向量指针作为输入传递给方法

时间:2011-08-06 10:02:00

标签: c++

我需要确定方法处理哪些属性(字符串)。所以,我设计了我的方法如下。

void method1( std::vector<String> * myVector )
{
   myVector = new std::vector<String>();  
   //do something;
   myVector->push_things;
}

所以,我会从topMethod()这样调用method1。

topMethod()
{
   std::vector<String> * aVector = 0;
   method1( aVector );
   //process aVector to identify its contents;
}

现在,method1()中的向量myVector正在填充。但它的内容无法在调用方法,即topMethod()。我不确定他们是如何被释放的。我觉得我正在使用new进行分配,所以理想情况下他们应该在通话后出现在来电地点。

请提供您对出了什么问题的看法。

4 个答案:

答案 0 :(得分:3)

因为您没有将指针作为参考传递:

试试这个:

void method1( std::vector<int>* & myVector )
{                          //  ^^^ note this!
   myVector = new std::vector<int>();  
   myVector->push_back(100);
}
//call it 
std::vector<int> *v;
method1(v);

或者这个:

void method1(std::vector<int> & myVector )
{
   myVector.push_back(100);  //myVector is not a pointer now!
}
//call it 
std::vector<int> v;
method1(v);

就个人而言,我更喜欢以下内容:

std::vector<int> method1()
{
   std::vector<int> myVector;
   myVector.push_back(100); 
   return myVector;
}
//call it 
std::vector<int> v = method1();

答案 1 :(得分:2)

除了告诉您解决方案错误的其他答案之外,我还将建议如何以适当的C ++方式执行此操作。 使用参考

void method1(std::vector<int>& v)
{
    v.push_things;
}

int main()
{
   std::vector<int> v;
   method1(v);
}

答案 2 :(得分:0)

您应该通过引用将指针传递给vector 您正在分配指向您传递的向量的指针的副本,而不是您传递的指针。

void method1( std::vector<int>* & myVector )

这应该解决它。

答案 3 :(得分:0)

如果你方法的工作是创建一个新的向量,那么返回它:

std::vector<int>* method1()

如果你需要额外的信号返回值,创建更多的向量等,请使用:

.. method1( std::vector<int>*& myVector, ..)

如果你方法的唯一工作是操纵一个向量:

.. method1( std::vector<int>& myVector)