Search code examples
c++vectorcharerase

c++ vector<char> erase() error, won't compile


#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>

using namespace std;

void makeVector();
void breakVector();

vector<char> asciiChar;
vector<char> shuffledChar;

int main(){
    srand((unsigned) time(NULL));
    makeVector();
    breakVector();
}

void makeVector(){
    for(char i = 32; i < 127; i++){
        asciiChar.push_back(i);
        cout << i << "  ";
    }
    cout << endl << endl;
}

void breakVector(){
    for(int i = 0; i < asciiChar.size(); i++){
        int j = rand() % asciiChar.size();
        shuffledChar.push_back(asciiChar.at(j));
        asciiChar[j].erase();                   //34 error *******
    }
    for(int i = 0; i < 95; i++){
        cout << shuffledChar.at(i) << "  ";
    }
}

.

...|31|warning: comparison between signed and unsigned integer expressions [-Wsign-compare]|
C:\Users\Owner\Documents\C++\asciiShuffle\main.cpp|34|error: request for member 'erase' in 'asciiChar.std::vector<_Tp, _Alloc>::operator[]<char, std::allocator<char> >(((std::vector<char>::size_type)j))', which is of non-class type '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}'|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

I am trying to delete the location in the vector that was used to assign a value to my other vector to avoid duplicate values. This code should be creating a vector and shuffling it's contents into another.

I have used .erase() in a similar function in another program and it worked for me but I don't understand this error message and my search results are turning up unrelated.


Solution

  • asciiChar[j].erase();
    

    You are trying to use the erase() method on a char element, and not on the vector itself.

    erase is a method of the vector class. So you have to use it on your asciiChar vector and not on an element of the vector.

    Also do note that you should never erase an element from a vector while you are iterating on its elements.

    What you want to achieve is probably this:

    while(asciiChar.size() > 0){
        int j = rand() % asciiChar.size();
        shuffledChar.push_back(asciiChar.at(j));
        asciiChar.erase(asciiChar.begin() + j);
    }