我有一个字符串,我需要抓住每个字符并进行一些检查。
std::string key = "test"
int i = 0;
while (key.at(i))
{
// do some checking
i++;
}
问题是,最终索引i将超出范围,因此系统将崩溃。我该如何解决这个问题?
谢谢!
答案 0 :(得分:1)
std::string key = "test"
for(int i = 0; i < key.length(); i++)
{
//do some checking
}
答案 1 :(得分:1)
for(auto i = key.cbegin(); i != key.cend(); ++i)
{
// do some checking
// call *i to get a char
}
答案 2 :(得分:0)
另一种解决方案是使用# In[30]:
import pandas as pd
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
h2o.init()
# Import a sample binary outcome train/test set into H2O
train = h2o.import_file("https://s3.amazonaws.com/erin-data/higgs/higgs_train_10k.csv")
test = h2o.import_file("https://s3.amazonaws.com/erin-data/higgs/higgs_test_5k.csv")
# Identify predictors and response
x = train.columns
y = "response"
x.remove(y)
# For binary classification, response should be a factor
train[y] = train[y].asfactor()
test[y] = test[y].asfactor()
# Train and cross-validate a GBM
model = H2OGradientBoostingEstimator(distribution="bernoulli", seed=1)
model.train(x=x, y=y, training_frame=train)
# In[31]:
# Test AUC
model.model_performance(test).auc()
# 0.7817203808052897
# In[32]:
# Generate predictions on a test set
pred = model.predict(test)
# In[33]:
from sklearn.metrics import roc_auc_score, confusion_matrix
pred_df = pred.as_data_frame()
y_true = test[y].as_data_frame()
roc_auc_score(y_true, pred_df['p1'].tolist())
#pred_df.head()
# In[36]:
y_true = test[y].as_data_frame().values
cm = pd.DataFrame(confusion_matrix(y_true, pred_df['predict'].values))
# In[37]:
print(cm)
0 1
0 1354 961
1 540 2145
# In[38]:
model.model_performance(test).confusion_matrix()
Confusion Matrix (Act/Pred) for max f1 @ threshold = 0.353664307031828:
0 1 Error Rate
0 964.0 1351.0 0.5836 (1351.0/2315.0)
1 274.0 2411.0 0.102 (274.0/2685.0)
Total 1238.0 3762.0 0.325 (1625.0/5000.0)
# In[39]:
h2o.cluster().shutdown()
并提供可处理每个字符的lambda函数,如下所示:
std::for_each()
此打印:
std::string key = "testing 123";
std::for_each(key.cbegin(), key.cend(), [](char c){ std::cout << c; });
答案 3 :(得分:-1)
您可以使用这样的for循环。
#include <string>
std::string str("hello");
for(auto &c : str) {
std::cout << c << std::endl;
}