C++ Vector Elements Count

霸气de小男生 提交于 2019-12-04 06:04:19

问题


In C++, using the vector header, how do I find the number of elements?

#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
    system("pause");
    return 0;
    primer(1000);
}

int primer(int max){
    vector<int> a;
    a[1]=2;
    for (int i=2;i<=max;i++){
    bool prime=true;
    for (int ii=1;ii<=#a;ii++) {
    if i/a[ii]==math.floor(i/a[ii]) {
    prime=false;
    }
    }
    if prime==true {
    a[#a+1]=i;
    }
    }
    for (i=1;i<=#a;i++) {
    cout << a[i]);
    }
}
}

I originally wrote the code for lua, and this is my attempt to translate it to C++. I would appreciate specifics, for example, a specific replacement for a bad line. I tried to replace #a with a.size, but it didn't work.

Revised:

#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
    primer(5);
    system("pause");
    return 0;
}

int primer(int max){
    vector<int> a;
    a[1]=2;
    for (int i=2;i<=max;i++){
    bool prime=true;
    for (int ii=0;ii<a.size();ii++) {
    if (i/a[ii]==floor(i/a[ii])) {
    prime=false;
    }
    }
    if (prime==true) {
    a.push_back(i);
    }
    }
    for (int iii=0;iii<=a.size();iii++) {
    cout << a[iii] << endl;
    }
}

It crashes without running. For what reason is this?


回答1:


a.size().

I would recommend using some sort of reference material, e.g. http://cplusplus.com/reference/stl/vector/.




回答2:


To answer your immediate question:

a.size();  // use size as a function

But there are several other things wrong with your code:

vector<int> a;
a[1]=2;

Ordinarily you need to set the size of a beforehand, since C++ must allocate space for it. You can use push_back() though, which will incrementally add space as needed.

Also, C++ arrays start counting at 0:

for (int ii=1;ii<=#a;ii++) {

This should be

ii = 0

And since arrays start at 0, they end at size() - 1, not size().




回答3:


for( int ii = 0; ii < a.size(); ++ii )

C and C++ array indexes start at zero and end at size-1, so you need to compare less-than, not less-than-or-equal-to. vector follows the same rule.




回答4:


Another obvious problem that needs pointing out:

int main()
{
    system("pause");
    return 0;
    primer(1000);
}

Your function is never going to be called. Your app will exit when main returns.




回答5:


 a[#a+1]=i;

changed to use size() becomes:

 a[ a.size() + 1 ] = i;

This is syntactically correct but guaranteed wrong. It should be:

 a.push_back(i);

Read the API referenced by Oli.



来源:https://stackoverflow.com/questions/4741629/c-vector-elements-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!