0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++ STL vectorのempty()は長さ0で真

Last updated at Posted at 2020-06-06

vectorは要素の長さが0であれば真を返します。v.empty()v.begin() == v.end()が同じ結果になるので当たり前ですが、初期化子リストを代入するとどうなるのだろうと気になったので。

いつもの書き方

# include <vector>
# include <iostream>
# include <iomanip>

using namespace std;

int main()
{
	vector<int> v1;
	vector<int> v2 = {};
	vector<int> v3 = {0};

	wcout << boolalpha << v1.empty() << endl; // true
	wcout << boolalpha << v2.empty() << endl; // true
	wcout << boolalpha << v3.empty() << endl; // false

	return 0;
}

清書版

代入演算子を伴わないリスト初期化type var {};wcoutの既定フラグ設定wcout.setfを使用しています。

# include <vector>
# include <iostream>
# include <iomanip>

using namespace std;

int main()
{
    vector<int> v1;
    vector<int> v2{};
    vector<int> v3{0};

    auto fmtflags = wcout.setf(wcout.boolalpha);
    wcout << v1.empty() << endl; // true
    wcout << v2.empty() << endl; // true
    wcout << v3.empty() << endl; // false
    wcout.setf(fmtflags);

    return 0;
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?