我有两个不同类型的载体,即
1. std::vector<project3::Vertex<VertexType, EdgeType>> Vertice2; //Contains a list of Vertices
2. std::vector<std::string>temp12;
我的要求是我想将Vertice2中的所有数据存储到temp12。尝试了很多不同的方法,但得到了错误。即使是铸造对我来说也没有用。
我尝试过的最新动态是temp.assign(g1.Vertice2.begin(), g1.Vertice2.end());
Error: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'project3::Vertex<VertexType,EdgeType>' to 'const std::basic_string<_Elem,_Traits,_Ax> &' c:\program files (x86)\microsoft visual studio 10.0\vc\include\xmemory 208 1 Project_3_Revised
答案 0 :(得分:5)
你有一个vector
个苹果,你试图存储在vector
个橘子中。但苹果不是橘子,这是你的基本问题。
您需要将temp
设为vector<Vertex...>
,或者需要将每个Vertex
对象转换为string
,然后存储生成的string
秒。如果您尝试将顶点填入vector<string>
而不进行转换,请将其放弃。你不能也不应该尝试这样做。你正试图把一艘战舰放进一个铅笔杯里。
如果您使用转换,那么使用std::transform
以及您自己设计的转换功能是一种非常简单的方法。
Psudocode如下:
std::string ConvertVertexToString(const Vertex& vx)
{
std::stringstream ss;
ss << vx.prop_a << " " << vx.prop_b;
return ss.str();
}
int main()
{
...
std::transform(Vertice2.begin(), Vertice2.end(), back_inserter(temp12), &ConvertVertexToString);
}
答案 1 :(得分:2)
C ++不向std :: string提供任何默认转换。 C ++的模板是强类型的,就像其他语言一样。
您需要创建一个方法或函数来将project3:Vertex转换为std :: string。
一旦有了这个,就可以使用C ++的转换函数。
std::transform(Vertice2.begin(), Vertice2.end(), temp12.begin(), my_function_to_make_strings);
答案 2 :(得分:1)
C ++不支持任意分配不同类型的对象。在大多数情况下,强制转换也不起作用,即使你强制它起作用(如<reinterpret_cast>
)也不安全。
您最好的选择是使用运算符重载和复制构造函数来明确定义您期望从对象中复制的行为。例如,当您将一个顶点分配给一个字符串时,不清楚应该复制哪些数据元素。
答案 3 :(得分:1)
你的基本问题是你有
project3::Vertex<VertexType, EdgeType>
,你想要的
std::string
。那你怎么把一个转换成另一个呢?
转换为字符串的常用解决方案
(std::string
或其他)是重载<<
运算符。所以
首先需要定义一个函数
std::ostream&
operator<<(std::ostream& dest,
project3::Vertex<VertexType, EdgeType> const& value)
这将定义转换为数据时的样子 一个字符串。一旦你有了这个,比如:
std::transform(
Vertice2.begin(), Vertice2.end(),
std::back_inserter(temp12),
(std::string (*)(
project3::Vertex<VertexType, EdgeType> const&)) boost::lexical_cast);
应该这样做。