小编use*_*490的帖子

使用throw来替换C++非void函数中的return

在C++函数中,returnthrow?替换是一个好习惯吗?例如,我有以下代码

// return indices of two numbers whose sum is equal to target
vector<int> twoSum(vector<int>& nums, int target) {
    for(int i=0; i<nums.size()-1; ++i)
        for(int j=i+1; j<nums.size(); ++j)
        {
            if(nums[i] + nums[j] == target) return vector<int>{i, j};
        }
    // return vector<int>{};
    throw "no solution";
}
Run Code Online (Sandbox Code Playgroud)

上面的代码用我的GCC 7.2编译.

c++ exception-handling

47
推荐指数
9
解决办法
4062
查看次数

转换具有多个参数的构造函数

在C++ 11中,没有explicit关键字的构造函数可用于将参数列表隐式转换为其类.例如:

class Date{
private:
  int d, m, y;
public:
  Date(int _d, int _m=0, int _y=0) : m(_m), d(_d), y(_y) {}
  friend bool operator==(const Date &x, const Date &y) {return  x.d==y.d;}
};

int main()
{
  Date x = {1,2,3}; // no error; using converting constructor
  x == 1; // no error; converting constructor turns int into Date object
  x == {1,2,3}; // error
}
Run Code Online (Sandbox Code Playgroud)

因为x == {1,2,3},我收到以下错误:

explicit.cc:16:10: error: expected primary-expression before ‘{’ token
       x=={1,2,3};
          ^ …
Run Code Online (Sandbox Code Playgroud)

c++ constructor type-conversion c++11

12
推荐指数
2
解决办法
440
查看次数

MPI_Bcast C++ STL 向量

为什么下面的代码不起作用?它适用于我的用户定义的类,但不适用于 STL 矢量。

std::vector<int> v(4);
MPI_Bcast(&v, sizeof(v), MPI_BYTE, 0, MPI_COMM_WORLD);
Run Code Online (Sandbox Code Playgroud)

我遇到分段错误:

[sdg:13611] Signal: Segmentation fault (11)
[sdg:13611] Signal code: Address not mapped (1)
Run Code Online (Sandbox Code Playgroud)

由于向量中的元素是连续存储的,为什么我不能使用 MPI_BYTE 发送 std::vector 作为一个整体?

c++ parallel-processing stl mpi

1
推荐指数
1
解决办法
1791
查看次数