简体   繁体   English

为什么我的向量中的字符串不更改值?

[英]Why Doesn't My String In My Vector Change Value?

I am trying to change the value of time in my vector of structs. 我正在尝试更改结构向量中的时间值。 The result should output 1430 as the value of shares[1].time though I get something different. 尽管我得到了一些不同的结果,结果应该输出1430作为shares [1] .time的值。

The shares is the name of my vector, I've already populated vector with values for each struct. 份额是我的向量的名称,我已经在向量中填充了每个结构的值。 Share is a struct which contains a string time. Share是一个包含字符串时间的结构。

//This is in the Share.cpp
vector<Share>shares  //vector of structs.

unsigned convTime = 1430;
std::stringstream out;

out << convTime;    //make convTime a string stream
shares[1].time = out.str();    


std::cout << shares[1].time;



struct Share
{
    //member all the information in the structure
    std::string date;
    std::string time;
    double price;
    double volume;
    double value;
    std::string condition; //not nessesary in this assignment
};

But my shares[1].time stays as its original value and not 1430. What could I be doing wrong? 但是我的share [1] .time仍然是原始值,而不是1430。我在做什么错了?

You have to actually put objects in the vector before using them. 使用对象之前,必须将对象实际放入向量中。 When you write: 当你写:

vector<Share> shares;

there are no objects in it yet. 里面还没有物体。 Going 展望

shares[1].time

causes undefined behaviour. 导致不确定的行为。 If you use the .at() function instead of [] then you get an exception instead of undefined behaviour. 如果使用.at()函数而不是[]则会得到异常而不是未定义的行为。

To put objects in the vector, either use push_back() , or shares.resize(num_objects) . 要将对象放入向量中,请使用push_back()shares.resize(num_objects)

Most likely, you have defined vector<Share> shares in Share.cpp, as you say, but also somewhere else ! 正如您所说,很可能已经在Share.cpp中定义了vector<Share> shares但也有其他地方

This violates the One Definition Rule. 这违反了一个定义规则。 Weird things may happen as a result. 结果可能会发生奇怪的事情。 One of the things that definitely could happen is that shares[1] in one file isn't the same as shares[1] in another. 绝对可能发生的事情之一是,一个文件中的shares[1]与另一个文件中的shares[1] You'd have two variables with the same name. 您将有两个具有相同名称的变量。 But, remember that this is a could happen . 但是,请记住,这是有可能发生的 Violating the One Definition Rule may break your program in all kinds of unexpected ways. 违反一个定义规则可能会以各种意外的方式破坏您的程序。

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

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