小编Anw*_*sha的帖子

C++ Ifstream对象等于nullptr但它不是指针?

我正在尝试使用打开文件失败的测试程序ifstream.代码如下: -

#include <iostream>
#include <fstream>
#include <type_traits>
using namespace std;
int main()
{
    ifstream ifs ("wrong_filename.txt");
    cout << boolalpha;
    cout << is_pointer<decltype(ifs)>::value <<"\n";
    cout << (ifs==nullptr);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是: -

false
true
Run Code Online (Sandbox Code Playgroud)

如果ifs不是pointer,那它又怎么样nullptr

c++

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

for_each&ranged base for on 2D array

我试图使用for_each基于范围的for循环打印2D数组.

我的程序是这样的: -

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
  //for_each (begin(a), end(a), [] (int x) { cout<<x<<" ";}); this code throws error

  for_each (begin(a[0]), end(a[2]), [] (int x) { cout<<x<<" ";});  //this code works well, why ?

  cout<<endl;

  for  (auto &row: a)  // without & for row, error is thrown
  {
     for (auto x:row)  // no & needed for x, why ?
     {
        cout<<x<<" ";
     }
  }
  return 0;
} …
Run Code Online (Sandbox Code Playgroud)

c++ arrays c++11

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

c ++ shared_ptr发布所有权

我们都知道我们可以在C++中轻松地将unique_ptr转换为shared_ptr.但是,如果我做了这样的转换怎么办:

unique_ptr<X> u=make_unique<X>();    // X is some class
shared_ptr<X> s=move(u);      // this works of course
Run Code Online (Sandbox Code Playgroud)

现在我想将指针的所有权转移s回去u.可悲的是,除此之外release() function in shared_ptr like in unique_ptr别无他法: -

u.reset(s.release());
Run Code Online (Sandbox Code Playgroud)

此外,这也无法奏效: -

u.reset(s.get());
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议我如何转换shared_ptrunique_ptr或至少释放所拥有的指针shared_ptr

c++ shared-ptr unique-ptr

5
推荐指数
2
解决办法
4062
查看次数

C++移动语义(和rvalue引用)与普通引用

在阅读有关std :: move语义和rvalue引用的一些文章时,我发现它们是因为复制数据是一项昂贵的工作而引入的.真的!复制很昂贵,但这与我们在C++中使用"REFERENCES"的原因不同.它们也只是帮助传递变量的地址并防止昂贵的复制过程.

那么为什么要引入std :: move和rvalue呢?我的意思是什么工作不能正常引用做前者可以做的?

我的问题主要涉及功能.我的意思是当你将一个变量传递给一个函数时,哪个更好?为什么?: - 1.通过左值参考2.使用移动通过右值参考

c++ move c++11

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

C++使用default_random_engine在循环中生成随机数

最近我正在尝试使用中random engines定义的C++生成随机数的程序#include<random>.我的计划如下: -

#include <iostream>
#include <random>
#include <chrono>
using namespace std;
int random (int lim)
{
    default_random_engine dre (chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution<> uid(1,lim);
    return uid(dre);
}
int main()
{
    for (int i=0;i<10;++i)
    cout<<random(100)<<" ";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

简单,绝对!但是当我尝试输出时,这些数字不那么随机: -

66 95 95 96 96 96 96 96 97 97
Run Code Online (Sandbox Code Playgroud)

当我稍微改变我的程序并声明default_random_engineas static或者它global然后我的输出是正确的,如下: -

62 53 21 38 7 51 46 40 86 12
Run Code Online (Sandbox Code Playgroud)

任何人都可以指出我的程序最初出现了什么问题吗?这些小变化如何帮助我获得更好的输出?

c++ random

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

标签 统计

c++ ×5

c++11 ×2

arrays ×1

move ×1

random ×1

shared-ptr ×1

unique-ptr ×1