c++ - 为什么我找不到集合论的正确输出?

标签 c++

enter image description here

我想使用数组或 vector 打印集合的基数以及元素的成员资格。

我能够找到基数,但找不到同一程序中的成员资格。

这是我的代码..

#include<iostream>
#include<vector>
using namespace std;

int main(){

    vector<int> v;
    int ch;
    int j;

    for(int i=1; cin>>j; i++){
        v.push_back(j);
    }

    cout << v.size();

    cout << " enter element you want to find whether it is a memebr or not: ";
    cin >> ch;

    for(int i=0; i < v.size(); i++){
        if(v[i] == ch){
            cout << "element found";
            break;
        }
    }
    return 0;
}

最佳答案

看看你所做的是在运行时在一个循环中获取输入,该循环也在条件验证位置。为了终止它,你给了一个字符。它为此抛出一个异常。所以你的程序没有按预期工作。永远不要那样做。始终询问大小,然后将循环迭代那么多次。这是有效的代码:

#include<iostream>
#include<vector>
using namespace std;

int main(){

vector<int> v;
int ch;
int j,temp;
int size;
cin>>size;
for(int i=1; i<=size; i++){
    cin>>temp;
    v.push_back(temp);
}


cout << " enter element you want to find whether it is a memebr or not: ";
cin >> ch;



for(int i=0; i < v.size(); i++){
    if(v[i] == ch){
    cout << "element found";
    break;
    }

    }
cout<<v.size();

    return 0;

    }

希望这对你有帮助:)

关于c++ - 为什么我找不到集合论的正确输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43290144/

相关文章:

c++ - 在 map 中排序(字典顺序)

c++ - vp9 编码器返回一个空数据包

c# - 在构建时自动将 C++ 库复制到 C# 项目? ( Visual Studio 2010)

c++ - 无法在 C++ 中初始化 Matlab dll

c++ - 如何从同一个类的另一个成员函数中调用仿函数?

c++ - 根据模板参数选择构造器

C++ 可变参数函数模板

c++ - 输入: int fd = open ("file");?时fd代表什么

c++ - 查找每个 ConnectedComponent 区域的邻域

c++ - "foo(int* pointer)"与 "foo(int* &pointer)"