将向量作为数组返回的正确方法是什么
我在这里有两个问题......我正在编写一个函数,它接收一个向量,并且它假设以数组形式返回...假设arrs为'0 1 2'.....
1.这是正确的方法吗?
2.然后现在我想加入returnArr函数中的一个额外元素(例如arrs.push_back(55)),使用我写的代码,对于这个'添加',我把它放在for循环之前或之后?我问这个,因为我似乎得到了不同的结果
请原谅我使用的简单语言,因为我还是C ++的初学者
我尝试了什么:
I have 2 questions here... I am writing out a function where it takes in a vector and it is suppose to return as array... Suppose arrs are '0 1 2'.....
1. Is this the correct way to do so?
2. Then now I had wanted to add in an additional element ( eg. arrs.push_back(55) ) within the returnArr function, using the code I have wrote, for this 'adding', do I put it before or after the for-loop? I asked this, because I seems to get different result
Pardon the simple language I used as I am still a beginner in C++
What I have tried:
int * returnArr ( vector<int> arrs )
{
cout << "[ " ;
for (int i = arrs.size() - 1 ; i >= 0 ; i--)
{
cout << i << " ";
}
cout << "]" << endl;
// Results : [ 2 1 0 ]
}
请尝试以下方法:
Try the following:
int* returnArr (vector<int>* arrs)
{
int i;
// create an array one larger than the number of elements in the vector
int* pArray = new int[arrs->size() + 1];
cout << "[ " ;
for (i = 0; i << (int)arrs->size(); ++i)
{
pArray[i] = arrs->at(i); // copy the vector value to the array
cout << pArray[i] << ", ";
}
pArray[i] = -1; // put a termination marker at the end of the array
cout << " ]" << endl;
return pArray; // return the array to the caller
}
试图解决愚蠢的降价处理器搞砸了什么
[/ edit]
[edit]
Trying to fix what the stupid markdown processor has messed up
[/edit]
正确的方法是返回向量并使用其数据 [ ^ ]成员当你需要访问原始指针时。
The correct way is returning the vector and using its data[^] member when you need to access the raw pointer.
有几件事我想发表评论。
1.做不传递vector参数作为传递值。
正确的方法 -(const vector< int>& arrs)
2.你可以就地反转向量,在这种情况下你需要删除第1点的const。std ::反转(arrs.begin(),arr.end());
3.你也可以通过反转将值复制到另一个向量。
这样你就可以简单地返回新创建的向量。
There are several things on which I wish to comment.
1. Do not pass the vector parameter as pass by value.
Right way -(const vector<int>& arrs)
2. You could reverse the vector in-place in which case you need to remove the const in point 1.std::reverse(arrs.begin(), arr.end());
3. You also could copy values to another vector by reversing it.
This way you can simply return the newly created vector.
vector<int> returnArr(const vector<int>& arrs)
{
vector<int> arrs2(arrs.size());
std::copy(arrs.rbegin(), arrs.rend(), arrs2.begin());
return arrs2;
}
4.这是以相反顺序显示矢量内容的另一种方式。 std :: copy(arrs.rbegin(),arrs.rend(),ostream_iterator< int>(cout,));