61.2k views
1 vote
Integer dataSize is read from input. Then, strings and integers are read and stored into string vector colorList and integer vector quantityList, respectively. Lastly, integer quantityThreshold is read from input.

Initialize lastPosition with -1.
Find the last element pair with a quantity not equal to quantityThreshold. If the element pair is found, assign lastPosition with the index of the element pair and output the color and quantity, separated by a space. End with a newline.
Ex: If the input is:
4
black 85 navy 86 teal 92 turquoise 91
85
Then the output is:
turquoise 91
last match found at # 3
-------------------------------------------------------------------------------------------------------------------------
#include
#include
using namespace std;
int main() {
int numElements;
int quantityThreshold;
int lastPosition;
int i;
cin >> numElements;
vector colorList(numElements);
vector quantityList(numElements);
for (i = 0; i < colorList.size(); ++i) {
cin >> colorList.at(i);
cin >> quantityList.at(i);
}
cin >> quantityThreshold;
//YOUR CODE GOES HERE!//
if (lastPosition == -1) {
cout << "No result" << endl;
}
else {
cout << "last match found at # " << lastPosition << endl;
}
return 0;
}

User TaylorR
by
7.9k points

1 Answer

4 votes

To find the last element pair with a quantity not equal to 'quantityThreshold', one can modify the code as:

C++

#include <iostream>

#include <vector>

using namespace std;

int main() {

int numElements;

int quantityThreshold;

int lastPosition = -1;

int i;

cin >> numElements;

vector<string> colorList(numElements);

vector<int> quantityList(numElements);

for (i = 0; i < colorList.size(); ++i) {

cin >> colorList.at(i);

cin >> quantityList.at(i);

}

cin >> quantityThreshold;

// Update lastPosition to the index of the last element pair with a quantity not equal to quantityThreshold

for (i = numElements - 1; i >= 0; --i) {

if (quantityList.at(i) != quantityThreshold) {

lastPosition = i;

break;

}

}

// Output the color and quantity of the last element pair with a quantity not equal to quantityThreshold

if (lastPosition != -1) {

cout << colorList.at(lastPosition) << " " << quantityList.at(lastPosition) << endl;

cout << "last match found at # " << lastPosition << endl;

} else {

cout << "No result" << endl;

}

return 0;

}

So, based on the code in the question, the main change is that the loop starts from the end of the 'colorList' and 'quantityList' vectors and iterates backwards.

This ensures that the last element pair with a quantity not equal to 'quantityThreshold' is found and assigned to 'lastPosition'.

User Kevin Aenmey
by
7.8k points

No related questions found