简体   繁体   English

c ++帮助将向量索引传递给函数

[英]c++ help passing a vector index to a function

I know how to pass a vector to a function, but how do I pass a vector index to a function, or at least specify which index the function is modifying. 我知道如何将向量传递给函数,但是如何将向量索引传递给函数,或者至少指定函数正在修改哪个索引。 For example, I'm working on a Car class and it has a vector if wheel pointers and in order to remove one of the wheels my function looks like this: 例如,我正在研究一个Car类,它有一个向量如果是指针,为了删除其中一个轮子,我的函数看起来像这样:

Wheel& remove() {
    for (int i = 0; i < wheels.size(); i++) {
        if (wheels[i].position == wheels.at(i)) {
            ??
        }

what do I need to pass to the function in order to specify which wheel I want removed? 我需要传递给函数以指定我想删除哪个轮子? When a wheel is removed, the position where it was is still there and can be filled by another wheel. 拆下车轮时,车轮的位置仍在那里,可以用另一个车轮填充。 Let's say for example the car had 4 wheels...if I wanted to remove the 2nd index in the wheel vector, what does the function argument for remove() need to take in order to do it? 比方说,例如汽车有4个车轮......如果我想要去掉车轮矢量中的第二个索引,remove()的函数参数需要采取什么来做呢? Should I pass in the vector and then the specific index....and if so, what does the syntax look like? 我应该传入向量然后传递特定的索引....如果是这样,语法是什么样的?

You can just pass an integer to specify which one you would like to remove 您只需传递一个整数即可指定要删除的整数

void RemoveWheel(int i)
{
    if( (i<wheels.size()) and (i>=0) )
        wheels.erase(wheels.begin()+i);
}

http://www.cplusplus.com/reference/stl/vector/erase/ http://www.cplusplus.com/reference/stl/vector/erase/

If you want to leave the space for another wheel than you should define wheels as a vector of pointers and just delete object at the i-th position and save NULL instead of it. 如果你想留下另一个轮子的空间,你应该将wheels定义为指针向量,只需在第i个位置删除对象并保存NULL而不是它。

vector<Wheel *> wheels;

void RemoveWheel(int i)
{
    if( (i<wheels.size()) and (i>=0) ) {
        delete wheels[i];
        wheels[i] = 0;
    }
}

Your question is not entirely clear to me, but to remove an element from a vector, given an index i, you can do this: 你的问题对我来说并不完全清楚,但是为了从矢量中删除一个元素,给定索引i,你可以这样做:

wheels.erase(wheels.begin() + i);

But this would be better: 但这会更好:

auto e = std::remove_if(wheels.begin(), wheels.end(),
             [](const Wheel & wheel) {
                 return wheel.position == wheel;
             });
wheels.erase(e,wheels.end());

Although I'm not sure if you want to remove every element that fits that criteria, or just the first. 虽然我不确定您是否要删除符合该条件的所有元素,或仅删除第一个元素。 If you would show the logic in pseudocode of what you want to do, that would help. 如果您要以伪代码的形式显示您想要做的事情,那将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM