C++ expected constant expression

前端 未结 8 1494
日久生厌
日久生厌 2020-11-30 10:42
#include 
#include 
#include 
#include 
#include 
using std::ifstream;
using namespace std;
         


        
8条回答
  •  生来不讨喜
    2020-11-30 11:21

    float x[size][2];
    

    That doesn't work because declared arrays can't have runtime sizes. Try a vector:

    std::vector< std::array > x(size);
    

    Or use new

    // identity::type *px = new float[size][2];
    float (*px)[2] = new float[size][2];
    
    // ... use and then delete
    delete[] px;
    

    If you don't have C++11 available, you can use boost::array instead of std::array.

    If you don't have boost available, make your own array type you can stick into vector

    template
    struct array {
      T data[N];
      T &operator[](ptrdiff_t i) { return data[i]; }
      T const &operator[](ptrdiff_t i) const { return data[i]; }
    };
    

    For easing the syntax of new, you can use an identity template which effectively is an in-place typedef (also available in boost)

    template 
    struct identity {
      typedef T type;
    };
    

    If you want, you can also use a vector of std::pair

    std::vector< std::pair > x(size);
    // syntax: x[i].first, x[i].second
    

提交回复
热议问题