You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 like template<typename T> instead)
  • You included stack_base.h which 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:

  1. We created a generic Vec2 template struct that works with any numeric type, making it flexible for different use cases
  2. We overloaded the + and - operators to handle component-wise arithmetic—this keeps the code clean and intuitive
  3. We added an output operator overload so we can print vectors directly to the console
  4. Removed the irrelevant stack_base.h include 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:25:39