Home > front end >  C : Can't add a char array to a deque?
C : Can't add a char array to a deque?

Time:09-28

I'm trying to add a char[] array to a deque, but when I execute the following code below:

#include <iostream>
#include <queue>
#include <deque>
#include <string>
#include <unistd.h>

using namespace std;

int main(int argc, char *argv[]){
    deque<char[]> q;
    char buffer[2];
    buffer[0] = 'a';
    buffer[1] = 'b';

    q.push_back(buffer);

    return 0;
}

I get the following error:

test.cpp: In function ‘int main(int, char**)’:
test.cpp:14:23: error: no matching function for call to ‘std::deque<char []>::push_back(char [2])’
   14 |     q.push_back(buffer);

This seems strange, considering that I can add other data types like strings and ints to the deque just fine.

CodePudding user response:

This seems strange, considering that I can add other data types like strings and ints to the deque just fine.

Just because you can store some types of elements in deques doesn't necessarily imply that you can store any type of elements in deques. There are requirements that the element types must meet. Arrays do not satisfy those requirements. You cannot store arrays as elements of deque. buffer is an array. It cannot be an element of a deque.

You can store class instances as elements though (although restrictions apply) in a deque and you can store arrays as member of a class. So, you can store such array wrapper class as an element of deque. The standard library provides a template for such array wrapper. It's called std::array. Example:

std::deque<std::array<char, 2>> q;
std::array<char, 2> buffer;
buffer[0] = 'a';
buffer[1] = 'b';

q.push_back(buffer);

P.S. std::array is the only standard container template that allows storing arrays as elements.

CodePudding user response:

If you want to use a variable length array you can use the in-built std::vector<T> type like you used the std::deque<T>:

#include <deque>
#include <vector>

int main(int argc, char *argv[])
{
    std::deque<std::vector<char>> q;

    std::vector<char> buffer;
    buffer.push_back('a');
    buffer.push_back('b');

    q.push_back(buffer);

    return 0;
}
  • Related