我的问题很简单:std :: vector元素是否保证是连续的?在order word中,我可以使用指向std :: vector的第一个元素的指针作为C数组吗?
如果我的记忆力很好,那么C++标准就没有这样的保证.但是,如果元素不连续,那么std :: vector要求几乎不可能满足它们.
有人可以澄清一下吗?
例:
std::vector<int> values;
// ... fill up values
if( !values.empty() )
{
int *array = &values[0];
for( int i = 0; i < values.size(); ++i )
{
int v = array[i];
// do something with 'v'
}
}
Run Code Online (Sandbox Code Playgroud) 如果我想要一个指向 int 向量向量中的元素的指针,我会写:
vector<vector<int>> a (5);
int* p1 = a[4].data();
Run Code Online (Sandbox Code Playgroud)
但是,当我编写以下内容时,它不适用于 bool 向量的向量(为什么?):
vector<vector<bool>> b(5);
bool* p2 = b[4].data();
Run Code Online (Sandbox Code Playgroud)
编译器输出以下错误消息:
Semantic issue: Error: Cannot initialize a variable of type "bool*" with an rvalue of type "void".
Run Code Online (Sandbox Code Playgroud)