我正在尝试删除堆栈中的最后N-1个元素,但是删除了第一个N-1。
这是程序的输出:
如果我们选择值为1的键“ 5”,则应将其后的所有元素从堆栈中删除,而所有先前的元素都将被删除。
删除元素的过程位于函数find_enth_from_bottom();
#include <iostream>
#include <stack>
using namespace std;
stack <int> stek;
void change_enth_from_bottom(stack <int>& smack, int en, int newvalue);
int find_enth_from_bottom(stack <int>& smack, int en);
int find_enth_from_bottom(stack <int>& smack, int en) {
long size = smack.size();
if (size < en) {
return -1;
}
for (int i = 0; i < size - en; i++) {
smack.pop();
}
return smack.top();
}
void change_enth_from_bottom(stack <int>& smack, int en, int newvalue) {
find_enth_from_bottom(smack, en);
smack.pop();
smack.push(newvalue);
}
int main() {
int position, value, counter = 0;
for (int i = 1; i <= 10; i++) {
int k_val = rand() % 10 + 1;
cout << i << ". " << k_val << endl;
stek.push(k_val);
}
cout << "Enter position: "; cin >> position;
cout << endl << "Enter new value: "; cin >> value;
change_enth_from_bottom(stek, position, value);
cout << "The value of the element with position " << position << " is now changed to " << find_enth_from_bottom(stek, position) << endl;
cout << "New stack interface" << endl;
while(!stek.empty()) {
counter++;
int a = stek.top();
stek.pop();
cout << counter << ". " << a << endl;
}
return 0;
}
答案 0 :(得分:0)
您可以在基础容器中进行任何操作。
#include <iostream>
#include <stack>
using container_t = std::stack<int>::container_type;
namespace detail
{
class stack_access : std::stack<int>
{
public:
using stack::c;
};
}
constexpr container_t std::stack<int>::* container_ptr = &detail::stack_access::c;
int find_enth_from_bottom(std::stack<int> & stack, int en) {
return (stack.*container_ptr)[stack.size() - en];
}
void change_enth_from_bottom(std::stack<int> & stack, int en, int newvalue) {
(stack.*container_ptr)[stack.size() - en] = newvalue;
}
int main() {
using std::cin;
using std::cout;
using std::endl;
std::stack<int> stack;
for (int i = 1; i <= 10; i++) {
int k_val = rand() % 10 + 1;
cout << i << ". " << k_val << endl;
stack.push(k_val);
}
int position, value, counter = 0;
cout << "Enter position: "; cin >> position;
cout << endl << "Enter new value: "; cin >> value;
change_enth_from_bottom(stack, position, value);
cout << "The value of the element with position " << position << " is now changed to " << find_enth_from_bottom(stack, position) << endl;
cout << "New stack interface" << endl;
while(!stack.empty()) {
counter++;
int a = stack.top();
stack.pop();
cout << counter << ". " << a << endl;
}
return 0;
}
Note: Failed to read get kotlin metadata for ...etc, and type converter