简体   繁体   English

如何使我的向量增长到最初未知的大小?

[英]How do I make my vector grow to initially unknown size?

How do I continue this vector forever till it ends?我如何永远继续这个向量直到它结束? I'm not sure because all my attempts were reacted with errors.我不确定,因为我所有的尝试都出现了错误。

Can someone give me an example how to do it correctly?有人可以举个例子如何正确地做到这一点吗? I've tried to google it, but didn't really find any answer我已经尝试谷歌它,但并没有真正找到任何答案

#include <algorithm>
#include <iterator>
#include <iostream> 
#include <string>
#include <iomanip>
#include <vector>
int main()
{
    std::vector<int> a(10); 

    for (int v = 0; v < a.size(); v++ ){
        
            std::cin >> a[v];
            if (a[v] == -1) {
                break;
            }
            
    }
    int x;
    for (int x = 0; x != -1;) {
        std::cout << "\n";
        std::cin >> x;
        bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
        if (exists == 1) {
            std::cout << "found" << " ";
        }
        else if (exists == 0) {
            std::cout << "not found" << " ";
        }
    }
}

You do it by establishing an initially empty vector then using push_back or emplace_back members to append properly-received user input to the vector.您可以通过建立一个最初为空的向量,然后使用push_backemplace_back成员到 append 正确接收到向量的用户输入来做到这一点。 In short, your code would end up looking like this:简而言之,您的代码最终将如下所示:

#include <algorithm>
#include <iostream> 
#include <vector>

int main()
{
    std::vector<int> a;
    int  x;

    while (std::cin >> x && x != -1)
        a.emplace_back(x);

    while (std::cin >> x && x != -1)
    {
        if (std::find(std::begin(a), std::end(a), x) != std::end(a))
            std::cout << "found\n";
        else
            std::cout << "not found\n";
    }
}

The pushback features of std::vector will allow you to achieve your goal. std::vector 的推回功能将使您能够实现目标。

https://en.cppreference.com/w/cpp/container/vector/push_backhttps://en.cppreference.com/w/cpp/container/vector/push_back

In short, using it looks like:简而言之,使用它看起来像:

a.push_back(myIntvariable);

Fill the variable from input beforehand.预先从输入中填充变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM