将元素向量分配给向量

时间:2018-09-02 03:51:05

标签: c++ vector

这是我编写的细分函数:

public double calculateWages  (int hoursWorked, double rateOfPay) {
     return hoursWorked * rateOfPay;
}

我必须使用vector作为函数。如果v2元素等于v3元素,我想为v1向量分配一个元素(不重复; push_back或v2 [0] = v1 [0]):

我尝试过:

vector<int> v1(const vector<int> &v2, const vector<int> &v3) {

  int v2_index = 0;
  int v3_index = 0;
  int v1_INDEX = 0;

  for(int i=0; i < v3.size(); ++i) {
    if(v2[v2_INDEX] == v3[v3_INDEX]) {
       int  x= v2[v2_INDEX];
       v1[v1_INDEX] = x;
       ++v1_INDEX;
     }
     if (v2[0] != v3[0]) {
       v2_INDEX++;
     }
     v3_INDEX++;
   }
}

它们都不编译。为什么不使用额外的库就可以将元素v2 [i]正确分配给-----> v1 [i]?

我收到以下错误:

v1.push_back(v2.push_back(i));
v1[v1_INDEX] = v2[v2_index];
int x = v2[v2_index]; v1.push_back(x);
v1[v2[v2_index]];

1 个答案:

答案 0 :(得分:0)

问题的症结在于,在C ++中,与Pascal不同,函数通过使用return语句返回值。在C ++中,不可能通过函数名称访问返回的对象。在您的代码中:

   v1[v1_index] = x;

v1引用函数本身,而不是返回的对象。因此,代码尝试访问函数v1是因为它是数组还是向量。这没有任何意义,因此也有错误:

<source>: In function 'std::vector<int> v1(const std::vector<int>&, const std::vector<int>&)':
<source>:12:19: warning: pointer to a function used in arithmetic [-Wpointer-arith]
        v1[v1_index] = x;
                   ^

要获得所需的功能,您可以定义返回的对象并在最后将其返回:

vector<int> v1(const vector<int> &v2, const vector<int> &v3) {

  int v2_index = 0;
  int v3_index = 0;
  int v1_index = 0;

  vector<int> ret;
  for(int i=0; i < v3.size(); ++i) {
    if(v2[v2_index] == v3[v3_index]) {
       int  x= v2[v2_index];

       // Bug: out of bounds
       ret[v1_index] = x;
       ++v1_index;
     }
     if (v2[0] != v3[0]) {
       v2_index++;
     }
     v3_index++;
   }
   return ret;
}

这可以编译,但是您仍然遇到严重的错误。该错误超出了访问ret的范围。更好的解决方案是抛弃v1_index并直接调用push_back()

   int  x= v2[v2_index];
   ret.push_back(x);

更好的是,使用range-for循环而不是使用v3_index变量来解决所有问题。它很简单:

for (auto v3_element: v3) {
  ... your code goes here...
}

无需维护索引,也无需访问v3[...]for已为您完成了所有工作。不幸的是,由于v2_index的递增方式,您无法摆脱它,但是不需要其他索引变量。

相关问题