18

この問題は、次のコードで明確になります。

#include <functional>
#include <iostream>
#include <vector>

int main() {
  //std::vector<int> a, b;
  int a = 0, b = 0;
  auto refa = std::ref(a);
  auto refb = std::ref(b);
  std::cout << (refa < refb) << '\n';
  return 0;
}

std::vector<int> a, b;の代わりにコメントを使用するとint a = 0, b = 0;、コードは GCC 5.1、clang 3.6、または MSVC'13 のいずれでもコンパイルされません。私の意見でstd::reference_wrapper<std::vector<int>>は、 は LessThanComparable に暗黙的に変換可能std::vector<int>&であるため、LessThanComparable 自体である必要があります。誰かが私にこれを説明できますか?

4

2 に答える 2

0

あなたはそれを確信していますか

std::vector<int> a, b;

それが想定されていることをしていますか?これを例にとります

#include <functional>
#include <iostream>
#include <vector>

int main() {
  std::vector<int> a, b;
  //int a = 0, b = 0;
  a.push_back(42);
  a.push_back(6);
  a.push_back(15);
  for (int ii=0; ii<43; ii++) {
    b.push_back(ii);
  }
  auto refa = std::ref(a);
  auto refb = std::ref(b);
  std::cout<<&refa<<std::endl;
  std::cout<<&refb<<std::endl;
  std::cout<<"Contents of vector A"<<std::endl;
  for(auto n : a)
  {
    std::cout<<' '<<n;
  }
  std::cout<<std::endl<<"Contents of vector b: ";
  for (auto n : b){
    std::cout<<' '<<n;
  }
  //std::cout << (refa < refb) << '\n';
  return 0;
}

その結果、

0x7fff5fbff0c0
0x7fff5fbff0b8
Contents of vector A
 42 6 15
Contents of vector b:  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

最終的に

std::vector<int> a, b;

a および b と呼ばれる 2 つの別個の整数ベクトルを作成します。どちらも内容を持ちません。これは、メンバ a と b を持つ単一のベクトルを宣言する方法ではありません。

int a=0, b=0;

a と b という 2 つの別々の整数を宣言します。それぞれの値は 0 です。これら 2 つのコード スニペットは、まったく異なる変数を宣言するため、同じ意味で使用しないでください。

于 2015-07-14T18:51:22.630 に答える