使用C ++ 14编译以下代码,但运行它会导致分段错误。这是由lambda函数捕获引起的(用问号标注)?这样做的正确方法是什么?提前谢谢。
import random
import sys
try:
randSeed = int(input('Enter Random Seed:\n'))
random.seed(randSeed)
except ValueError:
sys.exit("Seed is not a number!")
print('Welcome to Monty Hall Analysis')
print("Enter 'exit' to quit")
while True:
# Total Number of Games
testNum = input('How many tests should we run?\n')
valid = False
while not valid:
try:
if testNum == "exit":
sys.exit("Thank you for using this program.")
else:
testNum = int(testNum)
valid = True
except ValueError:
testNum = input('Please enter a number:\n')
pStay = 0
pSwitch = 0 # Also need a running count var for switch
numGame = 0
for numGame in range(1, testNum + 1):
doorList = ['C', 'G', 'G']
random.shuffle(doorList)
print('Game', numGame)
print('Doors:', doorList)
playerDoor = random.randint(0,2)
montyDoor = random.randint(0,2)
print('Player Selects Door', playerDoor+1)
while montyDoor == playerDoor or doorList[montyDoor] == 'C':
montyDoor = random.randint(0,2)
print('Monty Selects Door', montyDoor+1)
if doorList[playerDoor] == 'C':
var = 0
else:
var = 1
if var == 0:
#pStay+=1 - - Not sure why you have two increments for pStay.. only need one.
print('Player should stay to win.')
pStay += 1
if var == 1:
print('Player should switch to win.')
pSwitch += 1 # Also increment the pSwitch
# Print out the percentages
print('\n')
print("Percentage of times player should have STAYED: ",(pStay/testNum) * 100, "%")
print("Percentage of times player should have SWITCHED: ",(pSwitch/testNum) * 100, "%")
答案 0 :(得分:5)
发生分段错误是因为std::function
构造函数返回时Process::processFunc
引用的Foo
对象被销毁。要解决此问题,请Process
保留std::function
对象的副本。
struct Process {
Process(const std::function<void()>& processFunc)
: processFunc(processFunc) {}
// ...
std::function<void()> processFunc;
};