【问题标题】:c++ vector<char> erase() error, won't compile [duplicate]c ++ vector<char> erase()错误,无法编译[重复]
【发布时间】:2017-10-03 16:29:57
【问题描述】:
#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)) ===|

我正在尝试删除向量中用于将值分配给我的其他向量以避免重复值的位置。这段代码应该是创建一个向量并将其内容改组到另一个向量中。

我在另一个程序的类似函数中使用了 .erase(),它对我有用,但我不明白这个错误消息,而且我的搜索结果显示不相关。

【问题讨论】:

  • chars 没有成员,erase() 或其他。
  • 那么我不能不删除一个char类型的向量元素吗?
  • 不是这样的。通过迭代器执行此操作并在向量本身上调用erase()(如@Isuka 的回答)。

标签: c++ vector char erase


【解决方案1】:
asciiChar[j].erase();

您正在尝试在 char 元素上使用 erase() 方法,而不是在向量本身上。

erase是vector类的一个方法。所以你必须在你的 asciiChar 向量上使用它,而不是在向量的元素上。

另外请注意,您应该永远不要在迭代矢量元素时从矢量中删除元素。

你想要达到的大概是这样的:

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

【讨论】:

  • 谢谢,我还是不太了解。
猜你喜欢
  • 2015-01-04
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 2014-10-04
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多