在性能方面,什么会更快?有区别吗?它是平台依赖的吗?
//1. Using vector<string>::iterator:
vector<string> vs = GetVector();
for(vector<string>::iterator it = vs.begin(); it != vs.end(); ++it)
{
*it = "Am I faster?";
}
//2. Using size_t index:
for(size_t i = 0; i < vs.size(); ++i)
{
//One option:
vs.at(i) = "Am I faster?";
//Another option:
vs[i] = "Am I faster?";
}
Run Code Online (Sandbox Code Playgroud) 我们的编码指南更喜欢const_iterator,因为它们比正常情况下快一点iterator.看起来编译器会在您使用时优化代码const_iterator.
这真的是对的吗?如果是的话,内部真正发生的事情会变得const_iterator更快吗?
编辑:我写了一个小测试来检查const_iteratorvs iterator,发现不同的结果:
对于迭代10,000个对象const_terator,花费几毫秒(大约16毫秒).但并非总是如此.有两次相等的迭代.
在C++库数组中,在哪些情况下,拥有.begin()和.end()成员函数是有用的?
在cplusplus.com上,示例用法是遍历数组:
for ( auto it = myarray.begin(); it != myarray.end(); ++it )
Run Code Online (Sandbox Code Playgroud)
但
for (int i = 0; i < myarray.size(); i++)
Run Code Online (Sandbox Code Playgroud)
可以用于此.
我正在重构一些旧代码.有一个C风格的功能是这样的:(显然我在这里简化了它)
int LoadData(char** buf1, int* buf1Len, char** buf2, int* buf2Len) {
*buf1Len = DetermineLength1();
*buf1 = (char*)malloc(*buf1Len);
// Fill buf1
*buf2Len = DetermineLength2();
*buf2 = (char*)malloc(*buf2Len);
// Fill buf2
int result = 0; // Or some other INT depending of result
return result;
}
Run Code Online (Sandbox Code Playgroud)
现在,我想更新此代码以某种方式返回unique_ptr或等效,因此指针将由调用者自动管理,并且调用者将永远不会忘记释放内存.
我找不到一个好的解决方案,所以目前我已将代码更改为以下内容:
int LoadData(std::unique_ptr<char[]>* ubuf1, int* buf1Len, std::unique_ptr<char[]>* ubuf2, int* buf2Len) {
// same code as above, and finally:
ubuf1->reset(buf1);
ubuf2->reset(buf2);
return result;
}
Run Code Online (Sandbox Code Playgroud)
这看起来不太好,所以我想看看是否有更好的解决方案.因为我正在返回两个缓冲区,所以使用unique_ptras作为返回值不是一个选项.
有没有更好的方法呢?
假设我想依次访问C++容器中的所有元素,哪种方式最有效?我在下面的例子中说明了我的问题:
std::vector<int> abc;
abc.push_back(3);
abc.push_back(4);
...
...
for(int i=0; i<abc.size(); i++)
{
abc[i];
}
std::vector<int>::iterator it = abc.begin();
std::vector<int>::iterator itEnd = abc.end();
while(it != itEnd)
{
(*it);
it++;
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,正如您所看到的,两个方法用于访问C++容器中的元素,因此一个自然的问题是哪一个更有效.谢谢.
我目前正在和一些朋友一起从事一个 C++ 学校项目。
在我在 C++ 中有向量之前,我做了这样的事情来使用它们:
unsigned int i = 0;
while (i != myVector.size())
{
doSomething(myVector[i]);
i++;
}
Run Code Online (Sandbox Code Playgroud)
但是在这个项目中,我的朋友们看到我使用这样的向量并不高兴,并要求我使用迭代器。我不太喜欢迭代器,因为它们的语法很难记住,但我的朋友们说使用它们更好,因为它工作得更快。由于我们正在一个包含大量向量的大项目中工作,因此使用迭代器至关重要。
时间已经过去了,即使我仍然不记得它们的语法,我仍在使用它们,但我想看看迭代器方法是否真的比“无符号整数”方法更快。
所以我做了这两个程序:
第一个使用 unsigned int 方法的程序:
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::string str = "This is a string";
int i = 0;
std::vector<std::string> vec;
while (i != 10000000)
{
vec.push_back(str);
i++;
}
unsigned int j = 0;
while (j != vec.size())
{
std::cout << vec[j] << std::endl;
j++;
}
return (0);
}
Run Code Online (Sandbox Code Playgroud)
第二个程序使用迭代器方法:
#include <vector>
#include …Run Code Online (Sandbox Code Playgroud)