0
#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.

3
  • 1
    chars don't have members, erase() or otherwise. Commented May 5, 2017 at 9:04
  • So can I not delete a char type vector element? Commented May 5, 2017 at 9:07
  • Not like this. do it via iterators and call erase() on the vector itself (as in @Isuka's answer). Commented May 5, 2017 at 9:09

1 Answer 1

3
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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I still don't know very much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.