5

整数のキューがあるとしましょう。

#include <iostream>
#include <queue>
using namespace std;


int main() {

    int firstValToBePushed = 1;

    queue<int> CheckoutLine;

    CheckoutLine.push(firstValeToBePushed);

    cout << CheckoutLine.front();

    return 0;
}

上記のように整数ではなく、整数へのポインタを保持するキューを使用して、基本的に同じことを行うにはどうすればよいですか。複数の値を作成するためにループを作成する予定ですが、これはもっと単純な例です。

ありがとう、

4

4 に答える 4

5

それがライフタイム管理の場合は、次のようになります。

std::queue<std::shared_ptr<int>> CheckoutLine;
CheckoutLine.push(std::make_shared<int>(firstValeToBePushed))

キューがプロキシのように親切で、他の誰かが実際にオブジェクトの有効期間を所有している場合、間違いなく:

std::queue<std::reference_wrapper<int>> CheckoutLine;
CheckoutLine.push(firstValeToBePushed)

キューをどこにも公開せず、それが内部にある場合は、他の人が示唆しているように、ポインターを保存しても問題ありません。

ただし、ポインターのコレクションをクライアントに公開することは絶対にしないでください。これは、ポインターの寿命を管理する負担をそれらに任せているため、最悪のことであり、コレクションではより厄介です。

もちろん、プリミティブ型または POD の場合は、コピーするだけで問題ありません。ポインターを格納する必要はありません。Move セマンティクスを使用すると、POD 以外でも簡単に使用できます。ただし、複雑な構造を持っている場合や、Move セマンティクスをオブジェクトに実装できない場合を除きます。

#include <functional>forstd::reference_wrapper#include <memory>for std::shared_ptrstd::unique_ptrおよび友人。最新のコンパイラにアクセスできると仮定します。

于 2012-12-06T08:07:15.977 に答える
3

ループを追加します。

#include <iostream>
#include <queue>
using namespace std;

int main() {

queue<int*> theQueue;
char c = 'n';

while (c == 'n') {
  cout << "Enter \'n\' to add a new number to queue ( \'q\' to quit):";
  cin >> c;
  if ( c == 'q') {
    break;
  }
  else {
    int num;
    cout << "Enter an integer and press return: ";
    cin >> num;
    theQueue.push(new int(num));
  }
}

while( !theQueue.empty() ) {
  cout << theQueue.front() << ": " << *theQueue.front() << endl;
      delete theQueue.front();
  theQueue.pop();
}
return 0;
}
于 2012-12-06T08:08:39.620 に答える
1
#include <iostream>
#include <queue>
using namespace std;


int main()
{
int  value = 1337;

int* firstValeToBePushed = &value;


queue<int*> CheckoutLine;



CheckoutLine.push(firstValeToBePushed);


cout << *(CheckoutLine.front()) << "is at " << CheckoutLine.front();

return 0;

}
于 2012-12-06T08:05:49.143 に答える
0

よくわかりません。おそらくあなたはそれをしたいでしょう:

#include <iostream>
#include <queue>

using namespace std;

int main(){
    int firstValueToBePushed = 1;

    queue<int *> CheckoutLine;

    CheckoutLine.push(new int(firstValueToBePushed));

    cout << *CheckoutLine.front() << endl;

    return 0;
}
于 2012-12-06T08:06:50.700 に答える