我正在使用此命令行来编译我的程序。
clang++ -std=c++17 -O3 main.cpp -o main
我在 20 分钟前启动了编译器,但它只是挂起。我终止编译器,并尝试再次编译它,但它仍然挂起。如果我使用完全相同的命令行,但没有 -O3
编译器会立即完成,但使用 -O3
编译器会挂起。
它编译的代码比较简单,没有任何错误。这是怎么回事?
#include <ctime> // for time()
#include <cstdlib> // for srand(), rand(), size_t, EXIT_SUCCESS
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main()
{
vector<string> messages;
messages.push_back(string("“Blessed are those who are persecuted because of righteousness, for theirs is the kingdom of heaven.”"));
messages.push_back(string("“Let the little children come to me, and do not hinder them, for the kingdom of heaven belongs to such as these.”"));
/* Literally 10000 more quotes from the Bible. */
srand(time(NULL));
cout << messages[ rand() % messages.size() ] << endl;
return EXIT_SUCCESS;
}
这是怎么回事?
最佳答案
如果您想保留程序中的所有字符串(而不是从文件中读取它们),我将替换 std::vector<std::string>
与 const std::vector<std::string_view>
或者甚至是 const std::vector<const char*>
并用所有字符串初始化它:
#include <ctime> // for time()
#include <cstdlib> // for srand(), rand(), size_t, EXIT_SUCCESS
#include <iostream>
#include <string_view>
#include <vector>
int main() {
const std::vector<std::string_view> messages{
"“Blessed are those who are persecuted because of righteousness, for theirs is the kingdom of heaven.”",
"“Let the little children come to me, and do not hinder them, for the kingdom of heaven belongs to such as these.”",
/* Literally 10000 more quotes from the Bible. */
};
srand(time(NULL));
std::cout << messages[ rand() % messages.size() ] << '\n';
}
我没有足够的耐心等待编译器完成原始代码的编译。以上编译时间约为 1 秒。
注意:有一个 <random>
header 可以让您获得比 rand()
更好的伪随机数生成。 。您应该考虑使用它。你的程序的结尾看起来像这样使用:
std::mt19937 prng(std::random_device{}());
std::uniform_int_distribution<std::size_t> dist(0, messages.size() - 1);
std::cout << messages[ dist(prng) ] << '\n';
关于c++ - clang 编译器挂起 -std=c++17 -O3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70490618/