std :: array vs std :: vector细微差别

3 arrays vector c++11

我想弄乱std::array它,看看它有多么不同std::vector.到目前为止,我只发现了一个主要的区别.

Sentence sentence = { "Hello", "from", "GCC", __VERSION__, "!" };  
std::array<std::string, 10> a;
std::copy(sentence.begin(), sentence.end(), a.begin());

int i = 0;
for (const auto& e : a)
{
    i++;
    std::cout << e << std::endl;
}
std::cout << i << std::endl;

// outputs 10

i = 0;
for (const auto& e : sentence)
{
    i++;
    std::cout << e << std::endl;
}
std::cout << i << std::endl;

// outputs 5

for (int i = 0; i < a.size(); i++)
    std::cout << i << " " << a[i] << std::endl;

// outputs 0 Hello
// ...
//         4 !
//         5-9 is blank

for (int i = 0; i < sentence.size(); i++)
    std::cout << i << " " << sentence[i] << std::endl;

// outputs 0 Hello
// ...
//         4 !
// stops here


// The following outputs the same as above
i = 0;

for (auto it = a.begin(); it != a.end(); it++)
{
    std::cout << i << " " << *it << std::endl;
    i++;
}
std::cout << i << std::endl;
i = 0;
for (auto it = sentence.begin(); it != sentence.end(); it++)
{
    std::cout << i << " " << *it << std::endl;   
    i++;
}
std::cout << i << std::endl;
Run Code Online (Sandbox Code Playgroud)

因此,从我所看到的,std::arraysize而且max_size是多余的,但std::vectorsize,并capacity可以不同或相同.这甚至可以从这个引用中得到证实:

数组对象的size和max_size始终匹配.

那么为什么std::array有冗余尺寸功能呢?更重要的是,你会认为它std::array的尺寸不一定与std::vector尺寸相同,因为矢量具有容量吗?此外,这是否意味着std::arrays是安全的(即,它们是否像向量一样具有智能指针管理?)

Som*_*ude 6

使其与其他容器兼容.

这样你就可以拥有一个模板函数,它可以接收任何集合,并确保无论是a std::vector还是a,它都能正常工作std::array.