简体   繁体   中英

std::array error: Has no member named 'assign'

In the following code, the compiler complains as: struct std::array<double,5ul> has no member named 'assign' . Here , it seems possible. Why is it so? (Compiler: g++ 4.8.2)

#include <array>

int main()
{
    std::array<double,5> arr;
    arr.assign(4.); // error: has no member named 'assign'
    return 0;
}

array::assign() is a Visual Studio extension. You are compiling with g++. Check here standard g++ array

As already mentioned, there simply is no assign member to std::array .

The interesting question now becomes why ? After all, the other containers have an assign member method !

I would note that unlike other containers, std::array has a fixed size. If you use std::vector<T>::assign (which would be a close equivalent), the vector is resized appropriately to match the size of the sequence being assigned; with an array, however, that would be impossible:

  • what would you do if the sequence being assigned is shorter than the array ?
  • what would you do if the sequence being assigned is longer than the array ?

this would be counter-intuitive, as the question does not arise for the other containers since their size is just adapted on the fly.

For a similar reason, std::array does not have: reserve , capacity , clear , insert , emplace , erase , push / pop (and variants) or resize . All of them suppose a container which size may vary.

That is very simple, as you can see here there is no assign member function for an std array. There is however a member function called fill you should be able to use.

The assign method it is not a member of std::array . The member fill does what the assign did in TR1.

assign was originally part of std::tr1::array (from the TR1 ) and was changed to be fill circa the C++0x (now C++11) draft n2798 (2008).

This is not really a Microsoft extension, I would imagine that they have probably maintained this method for compatibility with, and support for tr1 implementations in production (the method implementations are exactly the same).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM