Windows平台下c ++中的向量问题 [英] problem with the vector in the c++ under the windows platform

查看:51
本文介绍了Windows平台下c ++中的向量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先生,我创建了用于访问结构元素的编码

编码:


sir i create the coding for accessing the element of the structure

coding:


#include "stdafx.h"
#include <vector>
#include <string>
using namespace std;
struct myStruct
{
	int iTemp1;
	int iTemp2;
};
int main(int argc, char* argv[])
{
	int iTemp = 0;
	int iLoop = 0;
	int iMark;
	vector <mystruct> *myvec;
	vector <mystruct>::iterator *it;
	cout<<"How many times wants to insert \n";
	cin>>iTemp;
	for(;iLoop<itemp;iloop++)>
	{
		myvec = new vector<mystruct>
		myStruct *mystr=new myStruct();
		cout<<"Enter the data for m1 \n";
		cin>>iMark;
		mystr->iTemp1 = iMark;
		iMark = 0;
		cout<<"Enter the data for m1 \n";
		cin>>iMark;
		mystr->iTemp2 = iMark;
		myvec->push_back(*mystr);
	}


	return 0;
}




此编码正常工作..

如果我尝试打印该值,则最后输入的元素只会出现..

请帮帮我.


重新格式化了正确的标签.
-E-




This coding working without no error..

if i try to print the value the last entered element only coming..

please help me.


Reformatted with proper tags.
-E-

推荐答案

除了PrafullaVedante所说的那样,您还不必要在堆上创建一个结构,然后忘记删除它.只需像这样在堆栈上创建它即可:
Apart from what PrafullaVedante said, you are also needlessly creating a struct on the heap, and then forgot to delete it. Just create it on the stack like this:
myvec = new vector<mystruct>; // <-- see Solution 1
    for(;iLoop<itemp;iloop++)>
{
    myStruct mystr; // <-- do not create this with new!
    cout<<"Enter the data for m1 \n";
    cin>>iMark;
    mystr.iTemp1 = iMark; // <-- changed ''->'' to ''.''
    iMark = 0;
    cout<<"Enter the data for m1 \n";
    cin>>iMark;
    mystr.iTemp2 = iMark; // <-- changed ''->'' to ''.''
    myvec->push_back(mystr); // <-- removed ''*''
}


请注意,无论如何std::vector::push_back()都将创建传递值的副本,因此无需自己创建myStruct的新实例.


Note that std::vector::push_back() will create a copy of the passed value anyway, so there is no need to create new instances of myStruct yourself.


将以下语句带出了for循环

Brought following statement out of the for loop

myvec = new vector;




您正在为每个交互创建一个新的向量.


您的代码应如下图所示:




You are creating a new vector for each interation.


Your code should look like

myvec = new vector;

for(;iLoop<itemp;iloop++)>
{

myStruct *mystr=new myStruct();
cout<<"Enter the data for m1 \n";
cin>>iMark;
mystr->iTemp1 = iMark;
iMark = 0;
cout<<"Enter the data for m1 \n";
cin>>iMark;
mystr->iTemp2 = iMark;
myvec->push_back(*mystr);
}


这篇关于Windows平台下c ++中的向量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆