C++中基于栈和队列实现向量加减的程序无报错但无法执行求助
解决C++向量逐分量加减的运行问题
Hey there, let's figure out why your vector component-wise operations aren't working even without compile errors. Looking at your code snippet, there are a few obvious gaps and issues we need to fix first:
- You've got an invalid, incomplete template declaration (
template<type...is not valid C++ syntax—you'll need something liketemplate<typename T>instead) - You included
stack_base.hwhich seems totally unrelated to vector math operations; this is likely a leftover from other code that could cause unexpected issues - Your code cuts off before defining a vector structure or implementing the actual addition/subtraction logic—without these core pieces, the program can't execute as you expect
Let's build a complete, working example from scratch that does exactly what you need:
#include <iostream> // Remove the unnecessary stack_base.h include since we don't need it for vector operations // Generic 2D vector struct (works with int, float, double, etc.) template<typename T> struct Vec2 { T x; T y; // Constructor to initialize vector components Vec2(T x_val, T y_val) : x(x_val), y(y_val) {} // Overload + operator for component-wise addition Vec2 operator+(const Vec2& other) const { return Vec2(x + other.x, y + other.y); } // Overload - operator for component-wise subtraction Vec2 operator-(const Vec2& other) const { return Vec2(x - other.x, y - other.y); } }; // Helper to print vectors easily template<typename T> std::ostream& operator<<(std::ostream& os, const Vec2<T>& vec) { os << "(" << vec.x << ", " << vec.y << ")"; return os; } int main() { // Test your example vectors Vec2<int> A(3, 5); Vec2<int> B(1, 7); Vec2<int> sum = A + B; Vec2<int> diff = A - B; std::cout << "A + B = " << sum << std::endl; std::cout << "A - B = " << diff << std::endl; return 0; }
What this code does:
- We created a generic
Vec2template struct that works with any numeric type, making it flexible for different use cases - We overloaded the
+and-operators to handle component-wise arithmetic—this keeps the code clean and intuitive - We added an output operator overload so we can print vectors directly to the console
- Removed the irrelevant
stack_base.hinclude to eliminate any unintended side effects
When you run this code, it will output exactly what you expected:
A + B = (4, 12)
A - B = (2, -2)
内容的提问来源于stack exchange,提问作者bicanul123
相关产品推荐
相关产品推荐

