简体   繁体   English

通过引用语法传递的C ++向量

[英]C++ Vectors Passing by Reference Syntax

I am having issues passing the the return values of my reference into the main function.The code is supposed to return both the the amount of even and odd numbers the user enters. 我在将引用的返回值传递给main函数时遇到问题,该代码应该返回用户输入的偶数和奇数的数量。 I think my syntax in the pass are wrong. 我认为我的密码语法错误。

  using namespace std;

int numOfOddEven(vector<int>);
int main ()
{
int numValues, odd;
vector<int> values;
cout << "Enter number of values: ";
cin >> numValues;

for(int count = 0; count < numValues; count++)
{
    int tempValue;
    cout << "Enter value: ";
    cin >> tempValue;
    values.push_back(tempValue);
}

 cout <<"Odd numbers: " << numOfOddEven(odd);
}cout <<"Even numbers: " << numOfOddEven(even);


int numOfOddEven(vector<int> vect)
{
int odd = 0;
int even = 0;

for (int i = 0; i < vect.size(); i++)
    if (i/2 == 1 )
        ++even;
    else
        ++odd;

return odd;
return even;
}

Handful of things I see wrong with this code 我认为这段代码有很多错误

  1. You cannot return two elements like you are trying 您不能像尝试一样返回两个元素
  2. You are not passing by reference anywhere 您没有在任何地方通过引用传递
  3. What you are passing to numofOddEven is not what the function is expecting(an int vs a vector ) 您传递给numofOddEven的不是函数所期望的( intvector

Learn how functions work, what pass by reference actually means, what return does, and what taking a modulus of a number means in c++. 了解函数的工作原理,引用传递的实际含义, return含义以及在c ++中采用数字模的含义。 Then try approaching this again. 然后尝试再次处理此问题。

You're calling with wrong parameters and using wrong logic 您使用错误的参数调用并使用错误的逻辑

 odd =numOfOddEven(values); //Use values
 cout <<"Odd numbers: " << odd;
 cout <<"Even numbers: " << values.size()- odd; //Get even count using this

In numOfOddEven just return the odd count numOfOddEven只返回odd

Fix Logic : - 修复逻辑:-

int numOfOddEven(vector<int> vect)
{
int odd = 0;
//int even = 0;

for (int i = 0; i < vect.size(); i++)
    if (vect[i]%2 != 0 )
        ++odd;

return odd;
 //return even;
}

Another approach would be to use std::count_if 另一种方法是使用std::count_if

int numodd = std::count_if(values.begin(), values.end(), 
                      [](int i) {return i % 2 != 0;});
int numeven = values.size() - numodd ;
int numOfOddEven(vector<int> & vect)
{
int odd = 0;
int even = 0;

for (int i = 0; i < vect.size(); i++)
    if (vect[i]%2 == 1 )
        ++even;
    else
        ++odd;

return odd;

}


int main ()
{
int numValues, odd;
vector<int> values;
cout << "Enter number of values: ";
cin >> numValues;

for(int count = 0; count < numValues; count++)
{
    int tempValue;
    cout << "Enter value: ";
    cin >> tempValue;
    values.push_back(tempValue);
}

 cout <<"Odd numbers: " << numOfOddEven(values);
 cout <<"Even numbers: " << numValues - numOfOddEven(values);
 cin.get();
 cin.get();
 return 0;
}

References are defined in the function declaration/signature. 引用在函数声明/签名中定义。 For instance: 例如:

void fct( int &ref1, int &ref2)
{
   ref1 = 1;
   ref2 = 2;
}

int ref1, ref2;
fct(ref1, ref2);

No need for any returns. 无需任何回报。 The compiler, when it sees the &, it considers it as a pointer but in code, you consider it as a variable. 编译器在看到&时,将其视为指针,但是在代码中,您将其视为变量。

To address the question in your subject: 要解决您的主题中的问题:

int numOfOddEven(vector<int> vect) { }

Add a & before vect : 在vect前添加&:

int numOfOddEven(vector<int> & vect) { }

Then vect will be passed by reference instead of copied. 然后vect将通过引用传递而不是复制。 In regards to your return values, pass them in as references also and then declare the function of type void: 关于返回值,也将它们作为引用传递,然后声明void类型的函数:

void numOfOddEven(vector<int> & vect, int & countodd, int & counteven) { }

Then just modify those variables in the function and don't return anything. 然后,只需在函数中修改这些变量,就不会返回任何内容。

First of all, you are not passing anything by reference in your existing code. 首先,您没有在现有代码中通过引用传递任何内容。 If you want to pass the vector by reference, you need to declare your function like this: 如果要通过引用传递矢量,则需要这样声明函数:

int OddCount(const std::vector<int>& v)
// ................................^ That denotes a reference
{
    return std::count_if(v.begin(), v.end(), [](int i)
    {
        return i % 2;
    });
}

int EvenCount(const std::vector<int>& v)
{
    return std::count_if(v.begin(), v.end(), [](int i)
    {
        return !(i % 2);
    });
}

NOTE : Your logic for determining an odd/even is fixed in both of the above functions. 注意 :在上述两个函数中,确定奇/偶的逻辑都是固定的。 Your method is not correct (unless you think 2 is the only even number). 您的方法不正确(除非您认为2是唯一的偶数)。

Second, you never declared an even vector (and there is no need to, nor is there a need to declare an odd vector). 其次,您从未声明过even矢量(也不需要声明odd矢量)。 So you should modify your output statements: 因此,您应该修改输出语句:

cout << "Odd Numbers:  " << OddCount(values) << std::endl;
cout << "Even Numbers: " << EvenCount(values) << std::endl;

If you want both values to be returned from a single function call, there are a few ways to do it. 如果要从一个函数调用中返回两个值,则有几种方法可以实现。 The "simplest" way would be to return a std::pair<int, int> : “最简单”的方法是返回std::pair<int, int>

std::pair<int, int> CountOddsAndEvens(const std::vector<int>& v)
{
    int evens = std::count_if(v.begin(), v.end(), [](int i)
        {
            return !(i % 2);
        });

    int odds = v.size() - evens;

    return std::make_pair(evens, odds);
}

Alternatively, you could pass them in as output parameters: 或者,您可以将它们作为输出参数传递:

void CountOddsAndEvens(const std::vector<int>& v, int& evens, int& odds)
{
    evens = std::count_if(v.begin(), v.end(), [](int i)
        {
            return !(i % 2);
        });

    odds = v.size() - evens;
}

Both of which would require you to make changes to your current output calls: 两者都需要您对当前的输出调用进行更改:

std::pair<int, int> results = CountOddsAndEvens(values);
std::cout << "Odds = " << results.second << ", Evens = " << results.first << std::endl;

Or 要么

int evens, odds;
CountOddsAndEvens(values, evens, odds);
std::cout << "Odds = " << odds << ", Evens = " << evens << std::endl;

The first place to look is the declaration: 首先要看的是声明:

int numOfOddEven(vector<int>);

This returns one int , not two. 这将返回一个int ,而不是两个。 You have to change something if you want to return two (independent) pieces of information. 如果要返回两条(独立的)信息,则必须进行一些更改。 If you want to return two ints, you could write a function with this type: 如果要返回两个整数,则可以编写以下类型的函数:

pair<int,int> numOfOddEven(vector<int>);

Then, at the end of the function, you can return with return make_pair(num_odds, num_evens) . 然后,在函数末尾,您可以返回return make_pair(num_odds, num_evens) Then, you would need also to do something like this to actually accept the returned values: 然后,您还需要执行以下操作才能实际接受返回的值:

tie(odd, even) = numOfOddEven(values);

But , that's probably too complex for a beginner. 但这对于初学者来说可能太复杂了。 You want to find another, roundabout, way to "return" two numbers from one function call. 您想找到另一种回旋处的方式,以从一个函数调用中“返回”两个数字。

void numOfOddEven(vector<int>, int&, int&);

Note the return type is not void . 请注意,返回类型不是void This function doesn't really return anything. 此函数实际上不会return任何内容。 But you can pass in your two variables odd and even by reference to this. 但是您可以通过引用此变量来传递oddeven When you say "passing by reference", this is probably what you mean. 当您说“通过引用”时,这可能就是您的意思。

... more code required ... [ community-wiki :-) ] ...需要更多代码... [community-wiki :-)]


But, again! 但是,再次! It's obvious that every number is odd or even. 显然,每个数字都是奇数或偶数。 Therefore, it is sufficient to just return one number, the odd number. 因此,仅返回一个数字,即odd就足够了。 Then you can calculate (within main ) that the number of even numbers is simply the total size of the vector minus the number of odd numbers. 然后,您可以(在main内)计算出偶数的数目就是向量的总大小减去奇数的数目。

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

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