replace_copy的效率问题

szn_409 szn_409 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
{
//replace:前两个参数为目标序列,第三个参数为被替换值,第四参数为替换值
const int size = 1e7;
vector<int> vecInt;
vecInt.resize(size);

fill(vecInt.begin(), vecInt.end(), 10);

int time0 = GetTickCount();
replace(vecInt.begin(), vecInt.end(), 10, 20);
time0 = GetTickCount() - time0; //time0 = 16

time0 = GetTickCount();
for (int i = 0; i < size; ++i)
{
vecInt[i] == 10 ? vecInt[i] = 20 : 0;
}
time0 = GetTickCount() - time0; //time0 = 468

//replace_copy的速度令人发指,比手工操作还慢
vector<int> vecInt1;
time0 = GetTickCount();
replace_copy(vecInt.begin(), vecInt.end(), back_inserter(vecInt1), 20, 30);
time0 = GetTickCount() - time0; //time0 = 3058

vector<int> vecInt2;
time0 = GetTickCount();
for (int i = 0; i < size; ++i)
{
if (vecInt[i] == 20)
{
vecInt2.push_back(30);
}
else
{
vecInt2.push_back(vecInt[i]);
}
}
time0 = GetTickCount() - time0; //time0 = 2808
printf("\n");
}

如上代码,为什么replace_copy的效率还不如手写的效率高?
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
szn_409
C++ 语言 65,213 成员 250,513 内容